Not a statement. Why not? [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-24 02:17:15

问题


When I attempted to compile the following Java program:

public class MyClass 
{
    static int f1() { return 10; }
    static int f2() { return 20; }

    public static void main(String args[])
    {
        int x = 10;
        (x <= 10) ? f1() : f2();
    }
}

I got the error:

/MyClass.java:9: error: not a statement
        (x <= 10) ? f1() : f2();
                  ^

Java language definition talks about statements as one of assignment, increment/decrement, method invocation or object creation. My erroneous "statement" involves method invocation and should, therefore work. In fact, if I have a single statement like:

f1();

the compiler compiles the program sans any whimper. Similarly, if I change the final line to:

int y = (x <= 10) ? f1() : f2();

then too, everything is hunky-dory.

As a final piece of info, neither C nor C++ bats an eyelid on:

 (x <= 10) ? f1() : f2();

回答1:


The ternary operator is used in expressions. For statements, you can use an if statement. That's how the syntax is defined. Period.



来源:https://stackoverflow.com/questions/56896918/not-a-statement-why-not

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