main( )
메서드의 시작 중괄호 {
에서 끝 중괄호 }
까지 위에서부터 아래로 실행하는 흐름을 가진다.제어문
은 이러한 실행 흐름을 개발자가 원하는 방향으로 바꿀 수 있도록 해주며, 연산 결과에 따라 블록 내부의 실행 여부가 결정된다.if문은 else블록과 함께 사용
되며, 조건식이 ture면 if문 블록이 실행되고, false면 else 블록이 실행된다.조건문이 여러 개인 경우 else if 블록이 사용
되고,모든 조건식이 false
일 경우 else 블록이 실행
되고 if문을 벗어나게 된다.public class IfEx {
public static void main(String[] args) {
int num = (int) (Math.random() * 20) + 1;
if (num % 2 == 0) {
System.out.println("1번째 조건식");
System.out.printf("num : %d, 2의 배수입니다.\n", num);
} else if (num % 3 == 0) {
System.out.println("2번째 조건식");
System.out.printf("num : %d, 3의 배수입니다.\n", num);
} else if (num % 5 == 0) {
System.out.println("3번째 조건식");
System.out.printf("num : %d, 5의 배수입니다.\n", num);
} else {
System.out.println("2 또는 3 또는 5의 배수가 아닙니다. num : " + num);
}
}
}
break는 다음 case를 실행하지 않고 switch문을 빠져나가게 해준다.
->
)와 중괄호로 사용한다.yield 키워드
로 값을 지정해 변수에 바로 대입 가능하다.public class SwitchEx {
public static void main(String[] args) {
String season = "겨율";
// Java 11 이전 문법
String food = "";
switch (season) {
case "봄" :
food = "딸기케이크";
break;
case "여름" :
food = "빙수";
break;
case "가을" :
food = "와플";
break;
default:
food = "떡볶이";
}
System.out.println(food); // 떡볶이
}
}
public class SwitchEx {
public static void main(String[] args) {
String season = "가을";
// Java 12부터
String food = switch (season) {
case "봄" -> "딸기케이크";
case "여름", "가을" -> "빙수, 와플";
default -> "떡볶이";
};
System.out.println(food); // 빙수, 와플
}
}
public class SwitchEx {
public static void main(String[] args) {
String season = "여름";
// Java 13부터
String food = switch (season) {
case "봄" -> "딸기케이크";
case "여름", "가을" -> {
String summerFood = "빙수";
yield summerFood + "," + "와플";
}
default -> "떡볶이";
};
System.out.println(food); // 빙수,와플
}
}
public class ForEx {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
System.out.println("hello world, i의 값 : " + i);
// hello world, i의 값 : 0
// hello world, i의 값 : 1
}
}
}
💡 실행순서
- 1) 초기화식
int i = 0;
실행- 2) 조건식
i < 2;
평가- 2.1) true면 실행문
System.out.println("hello world, i의 값 : " + i);
실행- 2.1.1) 증감식
i++
실행 → 2) 부터 반복- 2.2) false면 for문 종료
(,)
로 구분해 작성한다.public class ForEx {
public static void main(String[] args) {
// Q. for문을 이용해 1부터 100까지의 정수 중 3의 배수의 총합을 출력하는 코드를 작성하세요.
int total = 0;
for (int i = 1; i <= 100 ; i++) {
if (i % 3 == 0) {
total += i;
System.out.println(i);
}
}
System.out.println("3의 배수 총합 : " + total); // 3의 배수 총합 : 1683
}
}
중첩된 for문
이라고 한다.public class ForEx {
public static void main(String[] args) {
// Q. 중첩 for문을 이용해 방정식 4x + 5y = 60의 모든 해를 구해서 (x, y) 형태로 출력하여라. 단, x와 y는 10 이하의 자연수이다.
for (int i = 1; i <= 10 ; i++) {
int resultX = 4 * i;
for (int j = 1; j < 10; j++) {
int resultY = 5 * j;
if (resultX + resultY == 60) {
System.out.printf("(%d, %d)\n", i, j);
// (5, 8)
// (10, 4)
}
}
}
}
}
public class WhileEx {
public static void main(String[] args) {
/*
Q. while문과 Math.random() 메소드를 이용해 두 개의 주사위를 던져 (눈1, 눈2)형태로 출력
눈의 합이 5가 아니면 계속 주사위를 던지고, 눈의 합이 5이면 실행을 멈춘다.
*/
while (true) {
int firstDice = (int) (Math.random() * 6) + 1;
int secondDice = (int) (Math.random() * 6) + 1;
if (firstDice + secondDice == 5) {
break;
}
System.out.printf("(%d, %d)\n", firstDice, secondDice);
// (2, 2)
// (5, 6)
// (5, 3)
// (2, 4)
// (2, 5)
// (5, 4)
// (2, 6)
// (3, 1)
// (6, 4)
// (2, 1)
// (3, 6)
// (1, 2)
// (1, 3)
}
}
}
💡 실행순서
- 1) 조건식
ture
평가- 1.1) true면 실행문
int firstDice 부터 if조건문 ~ System.out.printf까지
실행 → 1) 부터 다시 반복- 1.2) false면 while문 종료
조건식에 ture 사용하면 무한 반복
하게 되는데, 이 경우 while문을 빠져나가기 위한 코드가 필요하다. 위 코드에서는 if 조건문
이 해당된다.import java.util.Scanner;
public class WhileEx {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int inputNumber;
do {
System.out.println("1 부터 9 까지의 숫자를 입력하세요.");
inputNumber = scanner.nextInt();
System.out.println(inputNumber);
} while (inputNumber != 3);
System.out.println("숫자 입력이 종료되었습니다.");
}
}
💡 실행순서
- 1) 실행문
do 블록
실행- 2) 조건식
inputNumber != 3
평가- 2.1) true면 1) → 2) 반복 실행
- 2.2) false면 do-while문 종료
반복문
을 실행 중지
하거나 조건문
을 종료
할 때 사용한다.중첩된 반복문
에서 break문은 가장 가까운 반복문만 종료시킨다.public class ForEx {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
if (j == 3) {
System.out.println("[ @ ]");
break;
}
}
System.out.println();
System.out.println("--- 바깥 for문 ---, i 값 : " + i);
}
}
}
public class ForEx {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
if (j == 3) {
continue;
}
System.out.print(" " + j + " ");
}
System.out.println();
System.out.println("--- 바깥 for문 ---");
}
}
}