为什么这个三元运算符在这里不起作用,但在 c 中却可以完美地工作?
import java.util.Scanner;
class Pack {
public static void main(String[] args) {
System.out.println("enter a number");
Scanner s=new Scanner(System.in);
int i=s.nextInt();
i%2==0?System.out.println("even"):System.out.println("odd");
}
}
因为在 Java 中不能像那样赋值语句。如果你像这样使用它,你的三元组就可以工作,
System.out.println(i%2==0 ? "even" : "odd");
从根本上说,Java 不是 C。
编辑
你在评论中问,我在哪里分配任何东西?
引用Equality, Relational, and Conditional Operators (The Java Tutorials) ,
Another conditional operator is ?:
, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition
is true
, assign the value of value1
to result
. Otherwise, assign the value of value2
to result
."
此外,Chapter 15. Expressions - Conditional Operator ? :
(JLS-15.25)说
It is a compile-time error for either the second or the third operand expression to be an invocation of a void
method.