我可以使用哪个变量来设置其值集?

use*_*139 1 java variables

我想使用一个只能在Java中定义一定数量值的变量.我以前见过这个变量,但我无法在网上找到它.例如,我做它可以是WIN,LOSE或TIE.谢谢.

Hov*_*els 6

您需要创建一个包含这三个项目或状态的枚举.

public enum GameResult {
  WIN, LOSE, TIE
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您创建一个GameResult变量,它只能有四种可能状态中的一种,null或上述三种状态之一:

private GameResult gameResult;  // at present it is null

// later in your code:
gameResult = GameResult.WIN;
Run Code Online (Sandbox Code Playgroud)

另请注意,枚举可以包含非常有用的字段和方法.

例如,

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;
  }
}
Run Code Online (Sandbox Code Playgroud)