Ternary operator in java vs c [duplicate]

夙愿已清 提交于 2019-12-02 09:54:34

问题


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.



来源:https://stackoverflow.com/questions/26708771/ternary-operator-in-java-vs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!