Given:
public class ColorTest {
public static void main(String[] args) {
String[] colors = {"red", "blue", "green", "yellow", "maroon", "cyan"};
int count = 0;
for (String c : colors) {
if (count >= 4) {
break;
} else {
continue;
}
if (c.length() >= 4) {
colors[count] = c.substring(0, 3);
}
count++;
}
System.out.println(colors[count]);
}
}
What is the result?
A.
Yellow
B.
Maroon
C. Compilation fails
D. A StringIndexOutOfBoundsException is thrown at runtime.
題解
第12行會編譯錯誤,原因在於第7行的if不管條件式有沒有成立,都會直接略過之後for迴圈的程式,直接跳出迴圈或是進入下一次的迴圈,所以第12行的程式永遠執行不到,在編譯階段時就會被檢查出來。