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 循环的条件式,会发生编译错误。