Ternary operator in java vs c [duplicate]

2020-04-20 21:38发布

问题:

Why does this ternary operator doesn't works over here but where as in c it works perfectly?

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");
        }
    }

回答1:

Because you can't assign a statement like that in Java. Your ternary would work if you used it like,

System.out.println(i%2==0 ? "even" : "odd");

Fundamentally, Java isn't C.

Edit

You ask in the comments, where am i assigning anything?

To quote 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."

Further, Chapter 15. Expressions - Conditional Operator ? : (JLS-15.25) says

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.