Given the code fragment:
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.
题解
Java 的 switch 只能用来判断 int 以下的整数、字符、枚举,或是字符串(Java 7 之后),因此题目的程序使用 boolean 的方式是错误的,必须要将其修改成正确的才行。
选项 A,正确。
选项 B,boolean 的值不能是数字 1。
选项 C,拿掉 break 也无济于事。因为 switch 本身的用法是错的。
选项 D,拿掉 default 也无济于事。因为 switch 本身的用法是错的。
