Given the code fragment:



String shirts[][] = new String[2][2];
shirts[0][0] = "red";
shirts[0][1] = "blue";
shirts[1][0] = "small";
shirts[1][1] = "medium";

Which code fragment prints red:blue:small:medium:?

A.

for (int index = 1; index < 2; index++) {
    for (int idx = 1; idx < 2; idx++) {
        System.out.print(shirts[index][idx] + ":");
    }
}

B.

for (int index = 0; index < 2; index++) {
    for (int idx = 0; idx < index; idx++) {
        System.out.print(shirts[index][idx] + ":");
    }
}
C.
for (String sizes : shirts) {
    for (String s : sizes) {
        System.out.print(s + ":");
    }
}
D.
for (int index = 0; index < 2;) {
    for (int idx = 0; idx < 2;) {
        System.out.print(shirts[index][idx] + ":");
        idx++;
    }
    index++;
}

題解

選項A,由於index和idx都是從1開始,所以只會輸出shirts[1][1]的內容,也就是「medium」字串還有「:」。

選項B,會輸出「small:」。

選項C,shirt的型態應為字串陣列「String[]」。

選項D,正確答案。