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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19837822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:36:14  来源:igfitidea点击:

Use switch statement to compare a string against an enum

javaenumsswitch-statement

提问by gm95

I'm making (my own version of)roulette with Java, and one of the types of bets a player can make is to choose the color that is going to be rolled. (Even is black, odd is red). Is there a way I can use a switch statement to compare a string against an enum?

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

This is what i'm trying to get but it's not letting me use the enum 'colors' in a switch statement.

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

采纳答案by Marko Topolnik

You must have an instance of an enum type (its member) on which you switch. You are trying to switch on the Enum class itself, which is a meaningless construct. So you probably need

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

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

BTW the name should be Colors, not colorsto respect the very important and non-optional Java naming convention.

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

回答by dimo414

You can get an enum from a string with Enum.valueOf(). Take care here, the other answers fail to mention that Enum.valueOf()will throw an IllegalArgumentExceptionif passed an string which isn't a valid member of the enum.

您可以从字符串中获取枚举Enum.valueOf()。在这里要小心,其他答案没有提到Enum.valueOf()会抛出一个IllegalArgumentExceptionif 传递的字符串,该字符串不是枚举的有效成员。

Be sure to properly format and indent your code, it helps us (and you!) read it and understand what's going on:

确保正确格式化和缩进您的代码,它可以帮助我们(和您!)阅读并了解发生了什么:

// 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!");
    }
  }
}

Note that we now return guessin both cases, which is somewhat redundant. At least with the example code you provided, you don't actually need to track colorVerifyat all, because the method will keep looping forever until a valid color is entered. You could replace the whole switchstatement in my method with simply return guess;as you know it's a valid guess as soon as Color.valueOf()returns a value.

请注意,我们现在guess在两种情况下都返回,这有点多余。至少使用您提供的示例代码,您实际上根本不需要跟踪colorVerify,因为该方法将永远循环,直到输入有效颜色。您可以switch简单地return guess;将我的方法中的整个语句替换为您知道它是一个有效的猜测,只要Color.valueOf()返回一个值。

In other words, you could clean your code up to:

换句话说,你可以清理你的代码:

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!");
      }
    }
  }
}

Notice that the method is staticnow, and uses a try-with-resourcesblock to close the Scanneronce you're done with it.

请注意,该方法static现在是,并使用try-with-resources块在Scanner您完成后关闭它。