【问题标题】:if statement inside the print statement?打印语句中的 if 语句?
【发布时间】:2013-11-05 03:56:36
【问题描述】:

如何在 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"} );
    }
}

【问题讨论】:

  • 与确切的问题无关,但我认为您的意思是实际打印出项目的数量,而不仅仅是“项目”或“项目”。

标签: java if-statement printing boolean system.out


【解决方案1】:

您不能在这样的表达式中编写if 语句。

但是,您可以使用Java's ternary operator ?:(在链接页面中向下滚动大约一半)嵌入条件表达式:

System.out.println("The list has: " +  ((array.size() > 1) ? "items" : "item"));

格式为:

booleanCondition ? valueIfTrue : valueIfFalse

【讨论】:

  • @mohamedghassar 如果您认为此答案有帮助,请不要忘记单击复选标记,尽管我知道您不能再等 5 分钟左右。