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=5的時候,第8行會拋出ArrayIndexOutOfBoundsException。

選項D,正確答案,標準的線性搜尋演算法。