Given:
public class Test {
public static void main(String[] args) {
int day = 1;
switch (day) {
case "7":
System.out.print("Uranus");
case "6":
System.out.print("Saturn");
case "1":
System.out.print("Mercury");
case "2":
System.out.print("Venus");
case "3":
System.out.print("Earth");
case "4":
System.out.print("Mars");
case "5":
System.out.print("Jupiter");
}
}
}
Which two modifications, made independently, enable the code to compile and run?
A. Adding a break statement after each print statement
B. Adding a default section within the switch code-block
C. Changing the string literals in each case label to integer
D. Changing the type of the variable day to String
E. Arranging the case labels in ascending order
题解
现有的程序会因为 switch 选择的整数数据型态和 case 的字符串数据型态不同而发生编译错误。
选项 A,在每个 case 的 print 叙述下加入 break 叙述并无法修正编译错误的问题。
选项 B,加入 default 选择也无济于事。
选项 C,将每个 case 所用的字符串改成整数,这样才可以符合 switch 的数据型态。
选项 D,将变量 day 的型态改成字符串也可以符合 switch 的数据型态。
选项 E,case 排序的顺序并不会影响到编译结果。
