enhancedJack
enhancedJack

Reputation: 275

Why can't I replace if statement with conditional operator (?:)?

I've been struggling to turn

private PlaneClass preferredClass;

if (preferredClass == PlaneClass.FIRST_CLASS)
    preferredClass = PlaneClass.ECONOMY_CLASS;
else
    preferredClass = PlaneClass.FIRST_CLASS;

into

preferredClass == PlaneClass.FIRST_CLASS ? 
                preferredClass = PlaneClass.ECONOMY_CLASS 
                               : preferredClass = PlaneClass.FIRST_CLASS;

The if-statement compiles. The conditional operator doesn't. (Error messages: 1. Type mismatch: cannot convert from PlaneClass to boolean 2. syntax error on token "=". And two other error...). Where did I go wrong?

Upvotes: 2

Views: 1782

Answers (3)

khelwood
khelwood

Reputation: 59113

The syntax is:

condition ? value1 : value2;

not

condition ? statement1 : statement2;

The conditional operator is an expression, not a statement. It doesn't execute statements like an if statement does: it returns a value.

What you mean is:

preferredClass = (preferredClass == PlaneClass.FIRST_CLASS ? 
            PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS);

Upvotes: 10

Sandeep Kaul
Sandeep Kaul

Reputation: 3267

It should be

preferredClass == PlaneClass.FIRST_CLASS ? 
             PlaneClass.ECONOMY_CLASS 
                           :  PlaneClass.FIRST_CLASS;

Upvotes: 1

AlmasB
AlmasB

Reputation: 3407

preferredClass = preferredClass == PlaneClass.FIRST_CLASS ? PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS;

will do the trick

Upvotes: 1

Related Questions