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 结构。三元操作符的格式如下:
判断式 ? 判断式成立时要回传的值 : 判断式不成立时要回传的值
三元操作符的「?」和「:」一定是成对出现的,因此选项 A、B、D 都错误,而选项 C 的条件逻辑符合题目给的条件程序。
