Given the code fragment:
String[] colors = {"red", "blue", "green", "yellow", "maroon", "cyan"};
Which code fragment prints blue, cyan, ?
A.
for (String c : colors) {
if (c.length() != 4) {
continue;
}
System.out.print(c + ", ");
}
B.
for (String c : colors[]) {
if (c.length() <= 4) {
continue;
}
System.out.print(c + ", ");
}
C.
for (String c : String[] colors) {
if (c.length() >= 4) {
continue;
}
System.out.print(c + ", ");
}
D.
for (String c : colors) {
if (c.length() >= 4) {
System.out.print(c + ", ");
continue;
}
}
题解
选项 B、C 是错误的 foreach 用法,会编译错误。
选项 A,会把所有字符串长度等于 4 的元素输出,是正确答案。
选项 D,会把所有字符串长度大于等于 4 的元素输出,不符合题目要求。
