lundi 27 mai 2019

How to convert an If Statement to a Ternary Operator expression

I am working with Java version "1.8.0_171". I am trying to convert this simple If statement to a ternary expression/operator:

private String player;   // a class variable
.     .    .     .     .     .    .    .     .     .
public String switchPlayer(String player) {
    if(this.player == "X")
        this.player = "O";
    else
        this.player = "X";
    return player;
}  

I tried to replace the If statement in this method with the following ternary statement:

player == "X" ? "O" : "X";

Java flags the == “X” in this statement with the following error:

Multiple markers at this line
- Type mismatch: cannot convert from String to 
 boolean
- Syntax error on token "==", invalid 
 AssignmentOperator  

This is the quick fix that Eclipse suggests:

String dummy = player == "X" ? "O" : "X";  

It seems a bit strange but, the ternary operator in Java has a left-side variable assignment requirement. The only error that I receive now is a simple warning that I am not using the variable dummy anywhere else in my code.

I am just going to use the simple If statement because the refactor value here is of small significance. I thought that I would post this anyway to see if there is any feedback from the community.

Aucun commentaire:

Enregistrer un commentaire