Given:



int x = 10;
if (x > 10) {
    System.out.println(">");
} else if (x < 10) {
    System.out.println("<");
} else {
    System.out.println("=");
}

Which of the following is equivalent to the above code fragment?

A.

System.out.printLn(x > 10 ? ">" : "<" : "=");
B.
System.out.println(x > 10 ? ">" ? "<" : "=");
C.
System.out.println(x > 10 ? ">" : x < 10 ? "<" : "=");
D.
System.out.printLn(x > 10 ? ">" ? "<" ? "=");
E. None of the above

題解

這題是在測驗三元運算子(?:)的用法。三元運算子在某些情況下可以取代if-else結構,而且可以獲得比if-else還要更好的效能。三元運算子的格式如下:

判斷式 ? 判斷式成立時要回傳的值 : 判斷式不成立時要回傳的值

三元運算子的「?」和「:」一定是成對出現的,因此選項A、B、D都錯誤,而選項C的條件邏輯符合題目給的條件程式。