on my way

이것이 자바다 Chapter04. 조건문과 반복 본문

Computer Science/JAVA

이것이 자바다 Chapter04. 조건문과 반복

wingbeat 2024. 3. 14. 14:29
반응형

4.1 코드 실행 흐름 제어

looping

실행 흐름 : main()메소드의 시작 중괄호({)에서 끝 중괄호(})까지 위에서부터 아래로 실행하는 흐름을 가지고 있다. 이 흐름을 개발자가 원하는 방향으로 바꾸는 것이 제어문이다.

조건문 : if, switch

반복 : for, while, do-while

 

4.2 if문

if (조건식) {

   실행문;

}

실행문이 하나면 {} 생략 가능

 

종류

1. if 

2. if-else if

3. if-else

 

이는 모두 하나의 if문이다.

 

package ch03.sec02;

public class IfElseIfElseExample {

	public static void main(String[] args) {
		int score = 3;
		if (score >= 90) {
			System.out.println("점수가 90보다 크다");
			System.out.println("등급은 A");
		} else if (score >= 80) {
			System.out.println("점수가 80보다 크다");
			System.out.println("등급은 B");
		} else {
			System.out.println("점수가 80미만이다");
			System.out.println("등급은 C");
		}
		
	}

}
// 주사위 굴려서 나오는 눈 1~6 중 하나
// Math.random() : 0<=x<1사이의 실수
// 원하는 숫자의 개수 곱함 + 시작값을 더한다.

package ch04.sec02;

public class IfDiceExample {

	public static void main(String[] args) {
		int num = (int)(Math.random()*6)+1;
		if (num==1) {
			System.out.println("1번이 나왔다.");
		} else if (num==2) {
			System.out.println("2번이 나왔다.");
		} else if (num==3) {
			System.out.println("3번이 나왔다.");
		} else if (num==4) {
			System.out.println("4번이 나왔다.");
		} else if (num==5) {
			System.out.println("5번이 나왔다.");
		} else if (num==6) {
			System.out.println("6번이 나왔다.");
		}
	}

}

 

 

4.3 switch문

		int a = 2;
		switch (a) {
		case 1:
			System.out.println("1입니다");
			break;
		case 2:
			System.out.println("2입니다");
			break;
		}

break를 매번 써야함. 너무 불필요하기 때문에 if 위주로 써라.

 

4.4 for문

for : ~동안 -> 반복할 때

실행 순서 :

for (1. 초기화 식 (변수 만들어놓고 1 대입) ; 2. 조건식 ; 4. 증감식) 

{ 3. 실행문 }

1-2-3-4-2-3-4-2-3-4-....-2(false일 때 까지)

for (int i=0, j=100; i<=50 && j>=50; i++, j--){
    System.out.println("Hello, world!");
}

초기화 식이나 증감식이 둘 이상 있을 수도 있다. 쉼표로 구분해서 작성한다.

 

public class SumFrom1To100Example {
    public static void main(String[] args) {
        int sum = 0;
        for (int i=0; i<=100; i++){
            sum += i;
        }
        System.out.println("1~"+(i-1)+" 합: "+sum);
    }
}

 

package ch04.sec04;

public class FloatCounterExample {
	public static void main(String[] args) {
		// float은 사용 하지마라. 부동 소수점이라 연산과정에서 0.1 표현 안됨. 9번만 반복된다
		for (float i = 0.1f; i <= 1.0f; i += 0.1f) {
			System.out.println(i);
		}
	}
}

위와 같이 증감식에서 정확하게 출력 되지 않는다.

 

4.5 while문

조건이 true일때만 반복한다. (false일 때는 반복하지 않는다.)

package ch04.sec05;

import java.util.Scanner;

public class KeyControlExample {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		boolean run = true;
		int speed = 0;

		while (run) {
			System.out.println("------------------------");
			System.out.println("1. 종속 | 2. 감속 | 3. 중지");
			System.out.println("------------------------");
			System.out.print("선택: ");

			String strNum = scanner.nextLine();

			if (strNum.equals("1")) {
				speed++;
				System.out.println("현재 속도 = " + speed);
			} else if (strNum.equals("2")) {
				speed--;
				System.out.println("현재 속도 = " + speed);
			} else if (strNum.equals("3")) {
				run = false;
			}
		}

		System.out.println("종료");
	}
}

4.6 do-while문

do {
	1.실행문;
} while (2. 조건식);

1. 실행문 2. 조건식 순서로 진행된다

import java.util.Scanner;
public class main {
    public static void main(String[] args) {
        System.out.println("메세지를 입력하세요. 종료하려면 q를 입력하세요.");
        Scanner scanner = new Scanner(System.in);
        String inputString;

        do {
            System.out.println(">");
            inputString = scanner.nextLine();
            System.out.println(inputString);
        } while (!inputString.equals("q"));
        
        System.out.println("종료");
    }
}

 

4.7 break문

for, while, do-while 반복문을 중지하거나, switch를 종료할 때 사용한다.

package ch04.sec06;

import java.util.Scanner;

public class DoWhileExample {
	public static void main(String[] args) {
		System.out.println("메세지를 입력하세요. 종료하려면 q를 입력하세요.");
		Scanner scanner = new Scanner(System.in);
		String inputString;

		do {
			System.out.println(">");
			inputString = scanner.nextLine();
			System.out.println(inputString);
		} while (!inputString.equals("q"));

		System.out.println("종료");
	}
}

4.8 continue문

for, while, do-while에서만 사용된다.

continue가 실행되면 for문의 증감식 또는 while, do-while문의 조건식으로 바로 이동한다.

 


확인문제

반응형