Given the code fragment:
public static void main(String[] args) {
int x = 5;
while (isAvailable(x)) {
System.out.print(x);
}
}
public static boolean isAvailable(int x) {
return x-- > 0 ? true : false;
}
Which modification enables the code to print 54321?
A. Replace line 6 with System.out.print(--x);
B. At line 7, insert x--;
C. Replace line 6 with --x; and, at line 7, insert System.out.print(x);
D. Replace line 12 With return (x > 0) ? false : true;
题解
程序第 12 行,在 isAvailable 方法内使用了「x--」,并不会影响到 main 方法的 x 变量,因为 Java 永远为「pass by value」。
选项 A,会使输出变成「43210」。
选项 B,可以成功输出「54321」。
选项 C,这样的逻辑和选项 A 是一样的。
选项 D,while 循环将不会运行。
