if statement inside the print statement?
Asked Answered
A

2

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"} );
    }
}
Aleuromancy answered 25/10, 2013 at 21:42 Comment(1)
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".Electrodialysis
M
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
Midvictorian answered 25/10, 2013 at 21:44 Comment(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.Electrodialysis
W
0

we Do this like

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

              ***conditon iftrue : iffalse***
Warmonger answered 13/2, 2023 at 5:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.