Given the code fragment:

public class Test {
    public static void main(String[] args) {
        boolean isChecked = false;
        int arry[] = {1, 3, 5, 7, 8, 9};
        int index = arry.length;
        while (~code1~) {
            if (arry[index - 1] % 2 == 0) {
                isChecked = true;
            }
            ~code2~
        }
        System.out.print(arry[index] + ", " + isChecked);
    }
}

Which set of changes enable the code to print 1, true?

A. Replacing <code1> with index > 0 and replacing <code2> with index--;
B. Replacing <code1> with index > 0 and replacing <code2> with --index; C. Replacing <code1> with index > 5 and replacing <code2> with --index ;
D. Replacing <code1> with index and replacing <code2> with --index ;

題解

程式最後的 arry[index] 需為 1;isChecked 需為 true。一開始 index 的值為 6。

選項 A,可以成功讓 index 變數在跳出 while 迴圈的時候數值為 0,並且修改 isChecked 變數的值為 true。

選項 B,理由同選項 A。

選項 C,while 迴圈只執行了一次,並讓 index 變數儲存的值修改成 5,isChecked 的值因為 arry[5] % 2 為 1 而維持 false,因此輸出結果會變成:

9, false

選項 D,index 並非是布林變數,因此無法直接作為 while 迴圈的條件式,會發生編譯錯誤。