6

How can I write an if statement inside the print statement?

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"} );
    }
}
Sujay
  • 6,753
  • 2
  • 30
  • 49
mohamed ghassar
  • 119
  • 1
  • 2
  • 7
  • Unrelated to the exact issue, but I take it that you meant to actually print out the number of items, not just "Items" or "Item". – Dennis Meng Oct 25 '13 at 21:45

2 Answers2

32

You can't write an if statement inside an expression like that.

However, you can use Java's ternary operator ?: (scroll down about half way in the linked page) to embed a conditional expression:

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

The format is:

booleanCondition ? valueIfTrue : valueIfFalse
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    @mohamedghassar Don't forget to click on the checkmark if you found this answer to be helpful, though I recognize you cannot do so for another 5 minutes or so. – Dennis Meng Oct 25 '13 at 21:52
0

we Do this like

System.out.println(20 > 30 "yes":"no");

              ***conditon iftrue : iffalse***
tech kid
  • 1
  • 2