Enhanced switch를 사용해 좀더간결한swich문을 작성할 수 있습니다.
:대신->를 사용하면break;를 생략할 수 있습니다.:와->는 하나의 switch 문에서 섞어서 사용할 수 없습니다.
switch (/*...*/) {
case /*...*/ -> /*...*/;
case /*...*/ -> /*...*/;
/*...*/
default /*...*/;
}
switch 문의 제약조건은 다음과 같습니다.
1.switch문의조건식결과는정수또는문자열이어야 한다.
2.case문의 값은정수,상수만 가능하며, 중복되지 않아야 한다.
- 만약
복잡한 객체를 switch에서 사용하고 싶거나, 좀더 까다로운 비교를 하고 싶다면enum을 사용할 수 있습니다.
public enum MyEnum {
ONE(1.1),
TWO(2.2),
THREE(3.3);
private final double value;
MyEnum(double value) {
this.value = value;
}
double myMethod(int n) {
return value * n;
}
}
public class SwitchTestMain {
public static void main(String[] args) {
MyEnum[] myEnum = MyEnum.values();
for (MyEnum e : myEnum) {
System.out.print("result = ");
switch (e) {
case ONE -> System.out.println(e.myMethod(1));
case TWO -> System.out.println(e.myMethod(2));
case THREE -> System.out.println(e.myMethod(3));
default -> System.out.println("wrong value");
}
}
}
}
result = 1.1
result = 4.4
result = 9.899999999999999
break로 현제 반복문을 빠져나갈 수 있지만, 중첩 반복문인 경우 여러개의 반복문을 빠져나갈 수는 없습니다.
- 반복문에
label을 추가하면break와continue에서 반복문을 지정할 수 있습니다.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int cnt = 0;
outer:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 5) break outer;
if (matrix[i][j] % 2 == 0) continue outer;
cnt++;
}
}
System.out.println("cnt = " + cnt);