자바 ocjap 문제 해설 - Switch Case
Given the code fragment:
public class Switch13 {
public static void main(String[] args) {
boolean opt=true;
switch(opt) {
case true:
System.out.print("True");
break;
default:
System.out.print("***");
}
System.out.println("Done");
}
}
Which modification enables the code fragment to print TrueDone?
A. Replace line 5 With String opt="true";
Replace line 7 with case "true":
B. Replace line 5 with boolean opt=1;
Replace line 7 with case 1:
C. At line 9, remove the break statement.
D. Remove the default section.
정답: A
해설:
switch() 의 괄호 안에는 boolean이 올 수 없고 정수, 스트링 또는 enum만 올 수 있다.
Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted
그래서 아래처럼 코딩하면 정답이 나온다.
public class Switch13 {
public static void main(String[] args) {
String opt="true";
switch(opt) {
case "true":
System.out.print("True");
break;
default:
System.out.print("***");
}
System.out.println("Done");
}
}
결과:
TrueDone