【问题标题】:Use switch statement to compare a string against an enum使用 switch 语句将字符串与枚举进行比较
【发布时间】:2013-11-07 13:58:13
【问题描述】:

我正在使用 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);

这是我想要得到的,但它不允许我在 switch 语句中使用枚举“颜色”。

【问题讨论】:

  • 假假假:while(colorVerify = false)!!!
  • 我认为他试图在最后一行中说应该是 == 而不是 == 并且他是正确的
  • 或者,更好的是,while(!colorVerify)
  • while(colorVerify = false) 甚至无法编译,因为它不返回布尔值!

标签: java enums switch-statement


【解决方案1】:

你必须有一个枚举类型的实例(它的成员),你可以在上面切换。您正在尝试打开 Enum 类本身,这是一个毫无意义的构造。所以你可能需要

colors col = colors.valueOf(colorGuess);
switch (col) ...

顺便说一句,名称应该是 Colors,而不是 colors,以尊重非常重要且非可选的 Java 命名约定。

【讨论】:

  • 并且cases必须是枚举类名限定
  • 不,枚举类名是隐含的。
  • @Bohemian:这实际上是不正确的;在这种情况下,只需红色和黑色即可。
  • 非常感谢。一段时间以来一直在使用不必要的 if/else if 语句
  • 警告,如果传递了一个无效的字符串,这将抛出一个IllegalArgumentException,OP 正在尝试处理该字符串。
【解决方案2】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多