Java一行如果不适用于打印 [英] Java one line if does not work for prints

查看:91
本文介绍了Java一行如果不适用于打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您写的内容如下:

    boolean condition;
    (...)
    String out = condition ? "true" : "false";
    System.out.println(out);

它有效。但如果你写

    condition ? System.out.println("true") : System.out.println("false");

您收到非声明错误。 正确的方式是写(括号的使用或是或不在一行超出了问题的范围):

you get a "not a statement" error. The "correct" way is to write (the usage of braces or "to be or not to be in one line" is out of the scope of the question):

    if (condition)
        System.out.println("true");
    else
        System.out.println("false");

为什么?一行如果 s必须总是返回一个值?

Why? The one line ifs must always return a value?

编辑:给大家指出

    condition ? System.out.println("true") : System.out.println("false");

语法不正确,是的,我得到了那个部分。我不是要求解决方案(虽然

is not a correct syntax, yeah I got that part. I am not asking for solutions (although the

    System.out.println(condition ? "true" : "false");

很不错。

@Andrew Tobilko在哪里说明了什么?那是是我感兴趣的。

@Andrew Tobilko where is that stated? THAT is what I'm interested in.

EDIT2 :接受的答案准确无误我想要的。谢谢

EDIT2: The accepted answer provides exactly what I wanted. Thanks

推荐答案

条件?System.out.println(true):系统.out.println(false);
不是声明。

condition ? System.out.println("true") : System.out.println("false"); is not a statement.

来自这里


在计算机科学中,三元运算符是一个运算符,它接受三个参数

System.out。 println(true) 不符合作为参数,因为方法 println()属于 void 类型。因此,它不是声明。

System.out.println("true") does not qualify to be an argument, as the method println() is of void type. Hence, it is not a statement.

请改用:

System.out.println(条件? true:false);

这篇关于Java一行如果不适用于打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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