Java 打印语句中的 if 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19599880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:39:51 来源:igfitidea点击:
if statement inside the print statement?
提问by mohamed ghassar
How can I write an if statement inside the print statement?
如何在打印语句中编写 if 语句?
public boolean checkEmpty()
{
if(array.isEmpty)
{
Sytem.out.println("The List is empty");
}
else
{
System.out.println("The list has: " + if(array.size() > 1)) {"Items"} + else {"item"} );
}
}
采纳答案by rgettman
You can't write an if
statement inside an expression like that.
您不能if
在这样的表达式中编写语句。
However, you can use Java's ternary operator ?:
(scroll down about half way in the linked page) to embed a conditional expression:
但是,您可以使用Java 的三元运算符?:
(在链接页面中向下滚动大约一半)来嵌入条件表达式:
System.out.println("The list has: " + ((array.size() > 1) ? "items" : "item"));
The format is:
格式为:
booleanCondition ? valueIfTrue : valueIfFalse