使用switch语句将字符串与枚举进行比较

14

我正在使用Java制作(自己版本的)轮盘赌游戏,玩家可以进行的一种下注类型是选择将会滚动的颜色。(偶数为黑色,奇数为红色)。是否有办法使用switch语句将字符串与枚举进行比较?

private enum colors{red, black};
private String colorGuess;
private boolean colorVerify = false;
public void getColorGuess(){
do{
Scanner in = new Scanner(System.in);
colorGuess = in.nextLine();
switch(colors){
case red:
    colorVerify = true;
    break;
case black:
    colorVerify = true;
    break;
default:
    System.out.println("Invalid color selection!");
    break;
}while(colorVerify = false);

我想要使用枚举类型“colors”在switch语句中,但无法实现。


1
错误 错误 错误: while(colorVerify = false)!!! - Tyco
我认为他想说的是最后一行应该是 a == 而不是 a ==,他是正确的。 - LionC
1
或者更好的是,while(!colorVerify) - dimo414
while(colorVerify = false) 连编译都过不了,因为它没有返回布尔值! - Giovanni Botta
2个回答

28
你必须使用枚举类型的实例(成员)作为switch语句中的表达式。你正在尝试在Enum类本身上进行switch,这是一个没有意义的构造。因此,你可能需要:
colors col = colors.valueOf(colorGuess);
switch (col) ...

顺便说一下,名称应该是Colors而不是colors,以遵守非常重要且不可选的Java命名规范。


1
并且案例必须是枚举类名称限定的。 - Bohemian
@Bohemian:实际上这是不正确的;在这种情况下,只需要红色和黑色即可。 - ljgw
@MarkoTopolnik 你说得对... 我过去不得不限定我的情况。只是试图记住为什么 :/ - Bohemian
@Bohemian 名称冲突,也许是吗?或者可能是使用遗留的非枚举常量(整数)。 - Marko Topolnik
5
注意,如果传递一个无效的字符串,这会抛出IllegalArgumentException异常,而 OP 正在尝试处理这种情况。 - dimo414
显示剩余2条评论

7
您可以使用Enum.valueOf()从字符串中获取枚举类型。但是要注意,其他答案未提及的是,如果传递给Enum.valueOf()的字符串不是该枚举类型的有效成员,则会抛出IllegalArgumentException异常。

请确保正确格式化和缩进您的代码,这有助于我们(以及您!)阅读并理解其功能:

// note the capitalization, and the singular 'Color'
private enum Color {RED, BLACK}; 

// At least with the code provided, you don't need colorGuess or colorVerify to be
// instance variables, they can be local to the method.  Limiting the amount of
// time a variable lives for (its scope) is critical for quality, maintainable code

public Color getColorGuess() {
  Scanner in = new Scanner(System.in); // this should be outside the while loop
  while(in.hasNextLine()) {
    // .toUpperCase() lets you type "red" or "RED" and still match
    String line = in.nextLine().toUpperCase();
    try {
      // Enum.valueOf() throws an exception if the input is not valid
      Color guess = Color.valueOf(line);

      switch(guess) {
        case RED:
          return guess; // return, rather than break, to exit the method
        case BLACK:
          return guess;
        // As long as your switch statement covers all cases in your enum, you
        // don't need a default: case, you'll never reach it
      }
    } catch (IllegalArgumentException e) {
      System.out.println("Invalid color selection!");
    }
  }
}

请注意,现在我们在两种情况下都返回guess,这有点冗余。至少对于您提供的示例代码而言,您实际上根本不需要跟踪colorVerify,因为该方法会一直循环,直到输入有效的颜色。您可以使用return guess;来替换我方法中的整个switch语句,因为一旦Color.valueOf()返回一个值,就知道它是一个有效的猜测。
换句话说,您可以简化代码如下:
public static Color getColorGuess() {
  try (Scanner in = new Scanner(System.in)) {
    while(in.hasNextLine()) {
      try {
        return Color.valueOf(in.nextLine().toUpperCase());
      } catch (IllegalArgumentException e) {
        System.out.println("Invalid color selection!");
      }
    }
  }
}

注意现在这个方法是static的,并且使用try-with-resources块来关闭Scanner一旦你用完它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接