I want to use a variable that can only have a set amount of values that I define in Java. I've seen this variable before but I cannot find it online any where. For example, I make it so it can be either WIN, LOSE or TIE. Thanks.
1 Answer
You need to create an enum, one with those three items or states.
public enum GameResult {
WIN, LOSE, TIE
}
Thus if you create a GameResult variable, it can have only one of four possible states, null or one of the three states above:
private GameResult gameResult; // at present it is null
// later in your code:
gameResult = GameResult.WIN;
Note also that enums can have fields and methods which can be quite useful as well.
e.g.,
public enum GameResult {
WIN(1), LOSE(-1), TIE(0);
private int score;
// a private constructor!
private GameResult(int score) {
this.score = score;
}
public int getScore() {
return score;
}
}