Given the code fragment:
public class ForTest {
public static void main(String[] args) {
int[] array = {1, 2, 3};
for (foo) {
}
}
}
Which three code fragments, when replaced individually for foo, enables the program to compile?
A. int i : array
B. int i = 0; i < 1;
C. ; ;
D. ; i < 1; i++
E. i = 0; i < 1;
题解
选项 A 为 Java foreach 的正确用法。
选项 B 也是标准的 for loop 用法,只是因为少了步进字段,i 变量的数值永远不会被改变,所以会变成无穷循环。
选项 C 也是正确的无穷循环。
选项 D,变量 i 没有事先声明。
选项 E,理由同选项 D。
