How can I write an if statement inside the print statement?
如何在print语句中编写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"} );
}
}
1 个解决方案
#1
25
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
#1
25
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