Given the code fragment:
4 5 6 7 8 9 10 11 12 13 14 | 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 result = "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只能用來判斷數值、字元,或是字串(Java 7)之後,因此題目的程式使用boolean的方式是錯誤的,必須要將其修改成正確的才行。
選項A,正確。
選項B,boolean的值不能是數字1。
選項C,拿掉break也無濟於事。因為switch本身的用法是錯的。
選項D,拿掉default也無濟於事。因為switch本身的用法是錯的。
留言