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