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 行的程序永远运行不到,在编译阶段时就会被检查出来。
