Reputation: 61
How would I go about making an If-like statment based on a Enum value.
My Enum gameStatus has the states WON, LOST, CONTINUE, and NOTSTARTED. I want to make a decision based on the current Enum value.
Something that would work like this:
if(gameStatus == WON)
{
point++;
}
else if(gameStatus == LOST)
{
point--;
}
Upvotes: 0
Views: 74
Reputation: 38531
You have a third option in your scenario, which is to define an abstract method on the enum class, and override the method so there is no if else or switch at all!
...
point = point + gameStatus.score();
...
enum STATE {
WIN {
@Override
public int score() {
return 1;
}
},
LOSE {
@Override
public int score() {
return -1;
}
}
public abstract int score();
}
Upvotes: 2
Reputation: 359786
You have a few reasonable options. You can either static import
the enum fields:
import static com.example.foo.GameStatus.*;
or instead qualify them with the enum type name, so that your code actually looks like
if(gameStatus == GameStatus.WON)
{
point++;
}
else if(gameStatus == GameStatus.LOST)
{
point--;
}
or you can avoid both if you use a switch
instead of if/else
:
switch (gameStatus) {
case WON:
point++;
break;
case LOST:
point--;
break;
}
Upvotes: 3