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排序的順序並不會影響到編譯結果。