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 迴圈將不會執行。
