컴퓨터 관련/JAVA 강의

java #5 BinaryString/Arguments/parseInt/제어문

승명 2016. 12. 18. 19:17

java #5 BinaryString/Arguments/parseInt/제어문

 
* BinaryString

- 정수를 2진수로 변환하는 Integer 클래스의 메소드
1
2
3
4
5
6
class  BinaryString{
     public static void main(String[] args)      {
          int i=1531315153;
          System.out.println(i+"를 이진수로 "+Integer.toBinaryString(i));
     }
}
cs

  • toBinaryString

    public static String toBinaryString(int i)
    Returns a string representation of the integer argument as an unsigned integer in base 2.

    The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.

    Parameters:
    i - an integer to be converted to a string.
    Returns:
    the string representation of the unsigned integer value represented by the argument in binary (base 2).
    Since:
    JDK1.0.2
출처 : http://docs.oracle.com/javase/7/docs/api/index.html


* Arguments

public static void main(String[] args) {
main : 코드를 실행하면 가장 먼저 실행되는 메소드
(String[] args) : Parameter (매개변수), 메소드 밖의 값을 안으로 넘겨주기 위한것, 프로그램을 동적으로 바꿈.
String[] : String의 배열
args : 배열의 이름


1
2
3
4
5
c:\> java T 10 안녕 3.5  <- java를 실행할 경우
 
String[] args[0] : 10
String[] args[1] : 안녕
String[] args[2] : 3.5
cs

* main method의 인자값(arguments : 외부값) 사용
- 인자값은 parameter(매개변수)를 타고 들어온다.
- 실행시 클래스 뒤에 띄어쓰기를 사용하여 여러개의 값을 구분하여 넣을 수 있다. (java 클래스명 값1 값2 값3 ...)
- 문자열로만 입력됨. 
- 인자값은 main method 안에서 문자열로 처리된다.
- main method 안에서는 매개변수명[번호]로 입력값 사용.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
     main method에 외부값 (aguments) 를 넣어서 사용하는 클래스
     실행법 : java Arguments 값 값 값 ....
*/
 
class Arguments {
     public static void main(String[] args)      {
          System.out.println( args[0] );     
          System.out.println( args[1] );
          System.out.println( args[2] );
          System.out.println( args[3] );
 
          System.out.println( args[0] + args[1] );
          /// 문자열을 정수로 변환
          int num1=Integer.parseInt(args[0]);
          int num2=Integer.parseInt(args[1]);
 
          System.out.println( num1 +"+"+ num2+"="+(num1+num2));
     }
}
cs

* parseInt란? 

- String에 저장된 문자열 형태의 숫자를 int형으로 변환하는 Integer클래스의 메소드이다.

- 아래는 java api(http://docs.oracle.com/javase/7/docs/api/index.html)에서 발췌

public static int parseInt(String s) throws NumberFormatException

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer



* 제어문

- 프로그램의 순차적인 흐름을 변경하는 문장

- 조건문, 반복문, 분기문이 있음

조건문 
조건에 따라서 코드를 수행할때
if, else, switch~case

단일if

조건에 맞을때에만 코드 수행

 

 

1
2
3
if(조건식){
조건에 맞을 때 수행 할 코드 
}
cs
if~else
둘중 하나를 실행해야 할 때

 

 

1
2
3
4
5
if(조건식){
조건에 맞을 때 수행 할 코드 
}else{
조건에 맞지 않을 때 수행 할 코드
}
cs

1
2
3
4
5
6
7
8
class IfElse{
     public static void main(String[] args){
          int num = 8;
          if(num%2==0){
          System.out.println("짝수");
          }else{
          System.out.println("홀수");
          }}}
cs

다중if(else~if)

여러개의 조건을 비교해서 코드를 실행

1
2
3
4
5
6
7
8
9
10
if(조건식){
조건에 맞을 때 수행문;
}else if(조건식){
조건에 맞을 때 수행문
}else if(조건식{
조건에 맞을 때 수행문
}......
}else{모든 조건에 맞지 않을 때 수행코드
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package day0211;
 
/**
* 문자열의 비교
* eclipse에서 Program Argument와 VM Argument의 사용
* @author SiSt
*
*/
public class StringIf {
 
     public static void main(String[] args) {
          //System.out.println(args[0]);
          //문자열은 같은지만 비교가능하다.
          //입력된 이름이 '김덕수'라면 반장을 출력하고
          //아니라면 '평민'을 출력하고 이름을 출력하는 프로그램
          if(args[0].equals("김덕수")){
               System.out.print("반장 ");
          }else{
               System.out.print("평민 ");
          }
          System.out.println(args[0]);
     }//main
 
}//class
cs

switch~case

- 정수만 비교할 때 사용하는 조건문
- jdk1.7부터 문자열까지 비교할 수 있다.
- 분기문인 break; 와 같이 사용할 수 있다. switch, for, while, do~while을 빠져나감.
- case의 상수는 인접한 수를 쓰거나 규칙이 있는 상수를 사용하는 것이 좀더 빠른 비교를 하게 된다.

1
2
3
4
5
6
7
8
9
10
11
 
switch(변수명){
         - 정수 : byteshortint (long은 제외)
         - 문자 : char
         - 문자열 : string
case 상수 :
       변수가 상수와 같을 때 수행코드
case 상수 :
default : 일치하는 상수가 없을 때 실행 할 코드.
}
 
cs
 
#1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package day0211;
 
/**
*  정수를 비교할 때 사용하는 switch~case문의 사용
*  JDK 1.7(javaSE7)에서 부턴 문자열도 비교 가능.
*/
public class TestSwitch {
     public static final int ZERO=0;
     public static final int ONE=1;
     public static final int TWO=2;//constant를 써서 case의 가독성을 높임
     public static void main(String[] args) {
     /*
          String i = "안녕";
     switch(i){//넣을 수 있는 변수는 byte, short, char, string
     case "안녕":
     }//end switch
     */
     int i = 0;
     switch(i){
     /* case에 상수를 직접 쓰면 비교하면 값의 가독성이 떨어진다.
     case 0 : System.out.println("0번");break;
     case 1 : System.out.println("1번");break;
     case 2 : System.out.println("2번");break;
     */
     case ZERO : System.out.println("0번");;break;
     case ONE : System.out.println("1번");;break;
     case TWO : System.out.println("2번");;break;
     default : System.out.println("case 없음");
     }//switch
}//main
}//class
cs

#2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package day0211;
 
//switch~case의 사용
 
public class TestSwitch1 {
     public static final int RANGE=10;
     public static final int GRADE_A_PLUS=10;
     public static final int GRADE_A=9;
     public static final int GRADE_B=8;
     public static final int GRADE_C=7;
     public static final int GRADE_D=6;
     public static void main(String[] args) {
 
          int score=10//점수를 저장할 변수
          /*
          char grade = 'F';//학점을 저장할 변수
          switch(score/RANGE){//10,9,8,7,6,5,4,3,2,1,0)
          case GRADE_A_PLUS:
          case GRADE_A : grade='A';break;
          case GRADE_B : grade='B';break;
          case GRADE_C : grade='C';break;
          case GRADE_D : grade='D';break;
          default : grade='F';
          }*/
          score=52;
          char grade= 64//65=A, 66=B ....
          switch(score / RANGE){
          case GRADE_D: grade++;
          case GRADE_C: grade++;
          case GRADE_B: grade++;
          case GRADE_A:
          case GRADE_A_PLUS: grade++; break;
          default:grade+=6;
          }//end switch
          System.out.println(score+"점의 학점은 "+grade);
     }//main
         
          }//class
cs

반복문

조건에 맞을때 까지 코드를 반복실행할 때
- 반복문을 빠져나가는 분기문은 break;
- 반복문의 수행을 건너뛸 때에는 continue;
- 조건을 잘못 부여하면 코드를 계속 수행하는 무한루프에 빠진다.(프로그램이 종료되지 않는다.)
  (강제정지/인터럽트.도스창=컨트롤+c)
- for, while, do~while

for

시작과 끝을 알 때 사용하는 반복문
※ 반복문 안에서 변수를 선언하지 않는다.

 

 

1
2
3
4
5
6
7
8
for(초기값;조건식;증감식){
        (시작값) (끝값)
반복 수행 문장
}
 
for(int i=0;i<5;i++){
S.O.P("안녕"+i);
}
cs

*무한loop
종료되지 말아야할 프로그램 작성할 
1
2
3
for( ; ; ){
반복수행 문장
}
cs
혹은
1
2
3
for(초기값; ;증강식){
반복수행문장
}
cs

이때, 무한루프 for문 아래의 코드는 죽은코드가 되어 에러 발생.

*for문 빠져나갈 때
for (①int i=0;②i<10;④i++){
③break;
}
④는 실행되지 않는다.

*실행 한번 건너뛰기

1
2
3
4
5
6
7
for(int i=0; i<5;i++){
if(i==2){
continue; <- i==2일때 코드를 수행하지 않고 i++로 건너뜀.
}
System.out.println();
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package day0212;
 
/**
* 다중 for문, 안쪽 for가 한번 실행될때 안쪽 for가 n번 실행된다.
*
* @author SiSt
*/
public class TestFor1 {
 
     public static void main(String[] args) {
 
          for (int i = 2; i <= 9; i++) {
               System.out.println(i + "단 시작");
               for (int j = 1; j <= 9; j++) {
                    System.out.println
                    (i + " * " + j + " = " + j * i + " ");
                    if (j == 9) {
                         System.out.println();
                    }// if
               }// for
               System.out.println(i + "단 끝");
               System.out.println();
          }// for
 
          for (int i = 1; i <= 9; i++) {
               for (int j = 2; j <= 9; j++) {
                    System.out.print
                    (j + " * " + i + " = " + j * i + "   ");
                    if (i * j < 10)
                         System.out.print(" ");
               }// for
               System.out.println();
          }// for
          System.out.println();
          for (int i = 0; i <= 3; i++) {
               for (int j = 0; j <= i; j++) {
                    System.out.print(i + " " + j + " ");
               }// for
               System.out.println();
          }// for
 
          System.out.println();
          for (int i = 0; i <= 3; i++) {
               for (int j = i + 1; j <= 4; j++) {
                    System.out.print(i + " " + j + " ");
               }// for
               System.out.println();
          }// for
 
          System.out.println();
          for (int i = 0; i <= 3; i++) {
               for (int j = i + 1; j <= 4; j++) {
                    System.out.print("*");
               }// for
               System.out.println();
          }// for
 
          // 무한loop
          /*
          * for( ; ; ){ System.out.println("무                                        한"); break; }//end for int k =0; //
          * break;가 없으면 에러뜸.
          */
          // 증가하는 수를 세는 무한 loop
          for (int i = 0;; i++) {
               System.out.println("무한" + i);
               break;
          }
 
          // continue는 반복문의 수행을 건너뛴다.//
          for (int i = 1; i < 10; i++) {
               if (i%3==0) {
                    System.out.print("짝 ");
                              continue;
               }//end if
                    System.out.print(i + " ");
                   
               }// end for
     }// main
}// class
cs

while

- 시작과 끝을 모를 때 사용
- 한번도 실행이 안될수 있고 최대 조건까지 수행

1
2
3
4
5
6
7
8
9
while(조건식= 관계연산자, 일반논리, method){
    반복수행문장;
}
-----------------------------------------
int i=0 //초기값
while(i<5){ //조건식
    S.O.P();
    i++ //증감식
cs

do~while

- 시작과 끝을 모를 때 사용
- 최소 한번 수행

1
2
3
4
5
6
7
8
9
do{
    반복수행문장 ;
}while(조건식);
------------------------------------
int i=0;// 초기값
do{
    S.O.P();
    i++; //증감식
}while(i<5); // 조건을 마지막에 물어본다.
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package day0212;
 
/**시작과 끝을 모를 때 사용하는 반복문
* while : 최소 0번 수행, 최대조건까지 수행
* do~while : 최소 1번 수행, 최대 조건까지 수행.
*
* @author SiSt
*/
public class TestWhile {
 
     public static void main(String[] args) {
         
          int i=0;//초기값
          while(i<10){//조건식
               System.out.println(i);
               i++;
          }//end while
          System.out.println("-------------------------------------");
          int j=1000;//초기값
          do{
              
               System.out.println(j);
               j++;
               }while(j<10);
         
     }//end main
 
}//class
cs

분기문

break, continue, return

'컴퓨터 관련 > JAVA 강의' 카테고리의 다른 글

java #7 문자열 비교(equals), Arguments   (0) 2016.12.18
java #6 패키지   (0) 2016.12.18
java #3, #4 Constant/형변환/API/연산자/진수   (0) 2016.12.18
java #2 java 기초2   (0) 2016.12.18
java #1 java 기초1   (0) 2016.12.18