Given:

public class TestLoop {
    public static void main(String[] args) {
        float myarray[] = {10.20f, 20.30f, 30.40f, 50.60f};
        int index = 0;
        boolean isFound = false;
        float key = 30.40f;
        // insert code here
        System.out.println(isFound);
    }
}

Which code fragment, when inserted at line 7, enables the code print true?

A.

while(key == myarray[index++]){
    isFound = true;
}
B.
while(index <= 4){
    if(key == myarray[index]){
        index++;
        isFound = true;
        break;
    }
}
C.
while(index++ < 5){
    if(key == myarray[index]){
        isFound = true;
    }
}
D.
while(index < 5){
    if(key == myarray[index]){
        isFound = true;
        break;
    }
    index++;
}

题解

选项 A,while 循环会在 key 和 myarray 中 index 索引对应的值一样才会运行。第一次进入 while 循环的时候,key = 30.40f、index = 0、myarray[0] = 10.20f,「30.40f」和「10.20f」并不相等,所以 while 循环不会运行,isFound 变量的值也就没有机会被改为 true 了。

选项 B,while 循环会在 index 变量小于等于 4 的时候运行。第一次进入 while 循环的时候,index = 0,所以循环会运行,但因 30.40f 不等于 10.20f,所以 if 条件式不成立,继续运行下一次循环。第二次进入 while 循环的时候,index 依然是 0,所以这个 while 循环是无穷循环。

选项 C,while 循环会在 index 变量小于等于 4 的时候运行,当条件式判断后,会将 index 的值加 1。由于这个 while 没有使用到 break 叙述,当 index=4 的时候,第 8 行会抛出 ArrayIndexOutOfBoundsException。

选项 D,正确答案,标准的线性搜索算法。