您可以使用 . 从字符串中获取枚举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
,因为该方法将永远循环,直到输入有效的颜色。您可以将我的方法中的整个switch
语句替换return guess;
为只要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
now,并且在您完成后使用try-with-resources块来关闭它。Scanner