JAVA 기초(4) 조건문, 반복문

이정민·2021년 10월 9일
0

조건문 - if, switch

  1. 자바에서 조건문은 if문과 switch문 두 가지 뿐이다.
  2. 모든 switch문은 if문으로 변경이 가능하지만, if문은 switch문으로 변경 할 수 없는 경우가 많다.
    (switch문이 if문 보다 제약조건이 많기 때문)

1. if문

String str = " ";
char ch = ' ';

if(ch=='c' || ch=='C'){} <-- OK!!
if(str=="c" || str=="C"){} <-- X
# 문자열의 배열을 비교할 때는 문자형 변수처럼 등가비교 연산자를 사용하면 안된다.
if(str.equals("c") || str.equals("C")){} <-- OK!!
# equals메서드를 이용해야 함
if(str.equalsIgnoreCase("c")){}
# 위에 식과 동일한 결과(대소문자를 구별하지 않고 문자를 비교함)

str="23"; ["23" -> '3']
if(str!=null && !str.equals("")){
  ch=str.charAt(0)
}
ch = '2'
# 1. 문자열을 문자로 바꾸는 식
# 2. 참조변수의 값이 null인지 먼저 확인하는 식을 앞에 둬야한다.
#    값이 null인 상태에서 메서드를 호출하면 error가 발생하기 때문  

2. 중첩 if 문

if (score >= 90) {
    grade = "A";
    
    if (score >=98) {
        grade += "+";
    } else if ( score < 94) {
             grade += "-";
    }
} else if (.....

3. switch 문

  1. if문의 조건식과 달리, 조건식의 계산결과가 int범위 이하의 정수만 가능
  2. 조건식과 일치하는 case문으로 이동 후 break문을 만날 때까지 문장들을 수행
    (break문이 없으면 switch문의 끝까지 진행한다.)
  3. case문의 값으로 int범위 이하의 정수만 가능하다.(리터럴, 상수만 가능)
  4. 일치하는 case문의 값이 없는 경우 default문으로 이동한다.(default문 생략가능)
int level = 3;

switch(lecel) {
    case 3 :
    grantDelete(); // 삭제권한을 준다.
    case 2 :
    grantWrite(); // 쓰기권한을 준다.
    case 1 :
    grantRead(); // 읽기권한을 준다.
}

사용자의 레벨이 높을 수록 더 많은 권한을 갖게 된다.(break문 생략) 간결하게

char  op = '*';

switch(op) {
    case '+' :
    	result = num1 + num2;
    	break;
    case '-' :
    	result = num1 - num2;
    	break;
    case '*' :
    	result = num1 * num2;
        break;
}
    

계산기 관련

switch(score) {
    case 100: case 99: case 98: case 97: case 96:
    case 95:  case 94: case 93: case 92: case 91:
    case 90:
    	grade = 'A';
        break;
    case 89: case 88: case 87: case 86:
    case 85: case 84: case 83: case 82: case 81:
    case 80:
    grade = 'B';
}

--------------------

switch(score/10) {
    case 10:
    case 9 :
    	grade = 'A';
        break;
    case 8 :
    	grade = 'B';
        break;
    case 7 :
    	grade = 'C';
        break;
    default :
    	grade = 'F';
}
    
    

Math.random()

Math 클래스에 정의된 난수 발생함수
0.0과 1.0 사이의 double값을 반환한다.(0.0 <= Math.random() < 1.0)

1~10범위의 임의의 정수를 얻는 식 만들기

1. 각 변에 10을 곱한다.

0.0 * 10 <= Math.random() * 10 < 1.0 * 10

0.0 <= Math.random() *10 < 10.0

2. 각 변을 int형으로 변환한다.

(int)0.0 <= (int)(Math.random() * 10) < (int)10.0

0 <= (int)(Math.random() *10) < 10

3. 각 변에 1을 더한다.

0 + 1 <= (int)(Math.random() * 10) + 1 < 10 + 1

1 <= (int)(Math.random() *10) + 1 < 11


실제 식

int score = (int)(Math.random() * 10) + 1;


반복문 - for, while, do-while

  1. 반복회수가 중요한 경우에 for문을 그 외에는 while문을 사용한다.
  2. for문과 while문은 서로 변경가능하다.
  3. do-while문은 while문의 변형으로 블럭{}이 최소한 한번은 수행될 것을 보장한다.
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);

//for 문
for(int i=1; i<=5; i++) {
    System.out.println(i);
}

// do-while 문
int i=0;

do {
	i++;
    System.out.println(i);
} while(i<=5);

// while 문

int i=1;

while(i<=5) {
	System.out.println(i);
    i++;
}

1. for문

for(;;) - 생략가능 , while(true){} - true적어줘야함(생략x)
[무한 반복됨)

for(int i=1, j=1; i<10 && i*j<50; i++, j+=2){}
  1. 변수 초기화에서 같은 타입의 변수인 경우에는 ,를 이용해서 선언할 수 있다.

  2. int, long과 같이 타입이 다른경우 선언할 수 없다.

  3. 증감식도 ,를 이용해서 2개 이상의 식을 사용할 수 있다.

public static void main(String[] args)
{
	int sum = 0;
    int i;
    
    for (i=1l i<=10; i++){
    	sum += i; //sum = sum + 1;
    }
    
    System.out.println("1에서" + i-1 + "까지의 합: " + sum);
}
// for문 밖에서도 변수 i를 사용하려면 밖에서 초기화를 시켜줘야한다.
// i-1을 한 이유는 끝에 i가 11이 되기 때문

2. do-while문

class FlowEx24 {
    public static void main(String[] args) throws java.io.IOException {
    	int input=0;
        
        System.out.println("문장을 입력하세요.");
        System.out.println("입력을 마치려면 x를 입력하세요.");
        do {
            input = System.in.read();
            System.out.print((char)input);
        } while(iuput != -1 && input != 'x');
   }
}

1. break 문

  1. 자신이 포함된 하나의 반복문 또는 switch문을 빠져 나온다.
  2. 주로 if문과 함께 사용해서 특정 조건을 만족하면 반복문을 벗어나게 한다.
int sum = 0;
int i = 0;

while(true) {
    if(sum > 100)
    	break;
    i++;
    sum += 1;
}
// break문을 만나서 while문 밖으로 나간다.

2. continue 문

  1. 자신이 포함된 반복문의 끝으로 이동한다. (다음 반복으로 넘어감)
  2. 전체 반복중에서 몇몇 경우를 제외하고 싶을 때 사용
for (int i=0; i<=10; i++) {
     if (1%3==0)
     	continue;
     System.out.println(i);
}

3. 이름 붙은 반복문과 break

  1. 반복문 앞에 이름을 붙이고, 그 이름을 break와 같이 사용함으로써 둘 이상의 반복문을 벗어나거나 반복을 건너뛰는 것이 가능하다.
Loop1 : for(int i=2; i<=9; i++) {
         for(int j=1; j<=9; j++) {
            if(j==5)
               break Loop1;
            System.out.println(i+"*"+j+"="+i*j);
         }
}         
profile
안녕하세요.

0개의 댓글