没有声明。为什么不? [英] Not a statement. Why not?

查看:90
本文介绍了没有声明。为什么不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译以下Java程序时:

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

我得到了错误:

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

Java语言定义将语句作为赋值,增量/减量,方法之一调用或对象创建。我错误的声明涉及方法调用,因此应该起作用。实际上,如果我只有一条语句:

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.

作为最后的一条信息,C和C ++都不会在以下方面引起人们的注意:

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

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


推荐答案

表达式中使用三元运算符。对于语句,可以使用if语句。这就是语法的定义方式。期间。

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

这篇关于没有声明。为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆