티스토리 뷰
java - switch문(multiple case, yield 키워드), do-while 문, break문(중첩된 반목문에서 바깥쪽 반복문까지 종료시키기), continue 문
Kodong's blog 2026. 3. 2. 14:39🟩 switch 문 (how to handle multiple case)
- No swich expressions (before Java 12)
If you omitted break keyword in case, the following case executes in a row.
In this case, it executes regardless of the value of case.
ex)
int currentTime = (int) (Math.random() * 11) + 7; // 7 8 9 10 11 12 13 14 15 16 17
switch (currentTime) {
case 7 :
System.out.println("출근 시간!");
break;
case 8:
case 9:
case 10:
case 11:
case 12:
System.out.println("오전 근무 시간!");
break;
case 13, 14 :
System.out.println("점심 시간!");
break;
case 15, 16, 17 :
System.out.println("오후 근무 시간!");
break;
default:
System.out.println("case에 해당 안됨.");
}
You can use both of them, "case 8, 9 : ~~" and "case 8 : (enter) case 9 : ~~".
+) If there no matching case, default will executed.
- switch expressions.
we can use arrrow operator.
int currentTime = (int) (Math.random() * 11) + 7; // 7 8 9 10 11 12 13 14 15 16 17
switch (currentTime) {
case 7 -> System.out.println("출근 시간!");
case 8, 9, 10, 11, 12 -> System.out.println("오전 근무 시간!");
case 13, 14 -> System.out.println("점심 시간!");
case 15, 16, 17 -> System.out.println("오후 근무 시간!");
default-> System.out.println("case에 해당 안됨.");
}
more readable!
or you can add "{}".
int currentTime = (int) (Math.random() * 11) + 7; // 7 8 9 10 11 12 13 14 15 16 17
switch (currentTime) {
case 7 -> {
System.out.println("출근 시간!");
}
case 8, 9, 10, 11, 12 -> {
System.out.println("오전 근무 시간!");
}
case 13, 14 -> {
System.out.println("점심 시간!");
}
case 15, 16, 17 -> {
System.out.println("오후 근무 시간!");
}
default-> {
System.out.println("case에 해당 안됨.");
}
}
🔵 yield keyword
The yield keyword lets us exit a switch expression by returning a value that becomes the value of the switch expression.
This means we can assign the value of switch expression to a variable.
ex)
char grade = 'A';
String message = switch (grade) {
case 'A' -> {
yield "Perfect";
}
case 'B' -> {
yield "Good";
}
default -> {
yield "Cheer up";
}
};
System.out.println(message);
In this code, we're assigning the value ("Perfact" or "Good" or "Cherr up") to the "message".
And, you have to write default keyword here when using yield keyword.
If we don't use yield keyword, the original code looks like below.
char grade = 'A';
String message;
switch (grade) {
case 'A' -> message = "Perfect";
case 'B' -> message = "Good";
default -> message = "Cheer up";
};
+) 추가적으로, for문을 쓸 때, 초기화식에서 부동 소수점을 쓰는 float타입을 사용하지 말아야한다. (부동 소수점을 쓰기 때문에 우리가 원하는 조건을 수행 못 할 수있다.)
for(float x=0.1f; x <= 1.0f; x+=0.1f) {
System.out.printIn(x);
}
// 코드의 의도는 10번 반복이지만, 실행하면 9번 반복된다.
// 이유는 앞서 설명했듯이, 부동 소주점 방식의 float타입은 연산과정에서
// 정확히 0.1을 표현하지 못하기 때문에, 증감식에서 x에 더해지는 실제 값은
// 0.1보다 약간 클 수 있다.
🟩 do-while 문
In do-while statement,
the code inside do will be executed first, then while determines whether repeating it or not depending on the result.
ex)
Scanner scanner = new Scanner(System.in);
String input;
do {
System.out.println(">> ");
input = scanner.nextLine();
} while (!input.equals("q"));
System.out.println("stop!");
🟩 break 문 (How to break external for statement in nested for loop)
How to break external for statement in nested for loop?
Add label to the external for statement and then add "break <that label>". That's it.
But, in real project, it's not used..!!
ex)
External : for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.println(i + " x " + j + " = " + i*j);
if (i == 2 && j == 2) {
System.out.println("'2 * 2'!!!!!!");
break External;
}
}
}
result)
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10
2 x 1 = 2
2 x 2 = 4
'2 * 2'!!!!!!
END.
'Java' 카테고리의 다른 글
| 자바 - 생성자 오버로딩, this(), 가변길이 매개변수, 메서드 오버로딩, final 필드와 상수, 패키지 (0) | 2026.03.06 |
|---|---|
| 자바 - 참조타입, 메모리 사용 영역, 타입에 따른 배열 기본값, main()메소드의 String[] 매개변수 용도 (0) | 2026.03.03 |
| 자바 - 연산자 (부호, 증감, 논리, 비트 논리, 삼항 연산자, 연산자 우선순위), 오버플로우, 언더플로우 (0) | 2026.03.01 |
| The application of bitwise AND operation (비트 논리곱(&) 연산) (0) | 2026.02.28 |
| 자바 - 타입 변환(자동, 강제, 연산식에서 자동 타입 변환) (1) | 2026.02.27 |