HYOJIN LIM
by HYOJIN LIM
1 min read

Categories

CH04. 조건문과 반복문

  1. 조건문
    • if문
    • if-else 문
    • switch문
       
    public class ConditionExample {
    	public static void main(String[] args) {
    		int x = 5;
       
    		// 1. if 문
    		if (x == 5) {
    			System.out.println("5입니다.");
    		}
       
    		// 2. if-else 문
    		x = 0;
       
    		if (x == 5) {
    			System.out.println("5입니다.");
    		} else if (x == 0) {
    			System.out.println("0입니다.");
    		} else {
    			System.out.println("5가 아닙니다.");
    		}
       
    		// 3. switch문
       
    		char ch = 'a';
       
    		switch (ch) {
    		case 'a':
    			System.out.println("a입니다");
    			break;
    		case 'b':
    			System.out.println("b입니다");
    			break;
    		case 'c':
    			System.out.println("c입니다");
    			break;
    		default:
    			System.out.println("a, b, c 이외의 알파벳입니다");
    			break;
    		}
       
    		// 4. break문이 없는 switch
    		ch = 'c';
    		switch (ch) {
    		case 'a':
    		case 'b':
    			System.out.println("a 또는 b입니다");
    			break;
    		case 'c':
    		default:
    			System.out.println("a, b 이외의 알파벳입니다");
    			break;
    		}
       
    	}
    }
    
  2. 반복문
    • for문
    • while문
    • do-while문
       
    public class LoopExample {
    	public static void main(String[] args) {
    		// 1. for문
    		int sum = 0;
    		for (int i = 1; i <= 10; i++) {
    			sum += i;
    		}
    		System.out.println("for 반복문으로 구한 합은: " + sum);
       
    		// 2. while문
    		sum = 0;
    		int i = 0;
    		while (++i <= 10) {
    			sum += i;
    		}
    		System.out.println("while 반복문으로 구한 합은: " + sum);
       		
    		// 3. do while문
    		do {
    			System.out.println("먼저 실행하고, 조건을 검사한다");
    			System.out.println("그러므로, 최소 한 번은 실행한다고 볼 수 있다!");
    		} while (false);
       		
       
    	}
    }