[Java] 제어문

handa·2023년 4월 14일
0


프로그램의 동작 흐름에 조건 / 반복을 통해 제어할 수 있는 실행문이다.

1. 조건문

자바의 조건문은 if-else 예약어를 사용하는 if문과 switch-case 예약어를 사용하는 switch문이 있다.

1-1. if문

조건식의 결과가 참과 거짓

public static void main(String[] args) {

	int score = 87;
    
    if (score >= 90) {
    	System.out.println("매우 우수합니다.");
    } else if (score >= 80) {
    	System.out.println("준수합니다.");
    } else if (score >= 70) {
    	System.out.println("노력이 필요합니다.");
    } else if (score >= 60) {
    	System.out.println("많은 노력이 필요합니다.");
    } else {
    	System.out.println("뭔가 잘못 되었습니다.");
    }
    
    if (score >= 90) System.out.println("매우 우수합니다.");
    else if (score >= 80) System.out.println("준수합니다.");
    else if (score >= 70) System.out.println("노력이 필요합니다.");
    else if (score >= 60) System.out.println("많은 노력이 필요합니다.");
    else System.out.println("뭔가 잘못 되었습니다.");
}

1-2. switch문

하나의 조건식으로 여러 경우의 수를 처리

public static void main(String[] args) {
        int score = 90;

        switch (score) {
            case 100: case 95: case 90:
                System.out.println("합격");
                switch (score) {
                    case 100:
                        System.out.println("이사");
                        break;
                    case 95:
                        System.out.println("사장");
                        break;
                    case 90:
                        System.out.println("부사장");
                }
                break;
            case 85: case 80:
                System.out.println("대기");
                break;
            case 75: case 70:
                System.out.println("패자부활전");
                break;
            default:
                System.out.println("불합격");
        }
}

2. 반복문

자바의 반복문은 for, while최소한 한 번은 수행되는 것을 보장하는 do-while이 있다.

2-1. for문

for문은 반복 횟수를 알고 있을 때 적합하다.

public static void main(String[] args) {
	String[] strArr = {"가", "나", "다", "라"};
    
    // 기존 for문
    for (int i = 0; i<strArr.length; i++) {
    	System.out.println(strArr[i]);
    }
    
    // 향상된 for문 - 배열 또는 컬렉션에만 사용가능
    for (String str : strArr) {
    	System.out.println(str);
    }
}

2-2. while문

while문은 조건식의 결과가 참인 동안 블럭 내 코드가 계속해서 반복된다.

public static void main(String[] args) {
	// for문
    for (int i = 0; i < 10; i++) {
    	System.out.println(i);
    }
    
    // while문
    int i = 0;
    while (i < 10) {
    	System.out.println(i);
        i++;
    }
}

2-3. do-while문

while문과 반대로 블럭을 먼저 수행한 뒤에 조건식을 평가해 반복 여부를 체크한다.
조건식의 결과가 거짓이어도 최소한 한 번의 수행은 보장한다.

public static void main(String[] args) {
	
}

3. 선택과제 구현

https://github.com/handsun000/JAVA-STUDY

profile
진짜 해보자

0개의 댓글