gm9*_*m95 9 java enums switch-statement
我正在制作(我自己的版本)轮盘赌用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);
Run Code Online (Sandbox Code Playgroud)
这就是我想要的,但它并没有让我在switch语句中使用枚举'colors'.
Mar*_*nik 16
您必须具有要切换的枚举类型(其成员)的实例.您正在尝试打开Enum类本身,这是一个毫无意义的构造.所以你可能需要
colors col = colors.valueOf(colorGuess);
switch (col) ...
Run Code Online (Sandbox Code Playgroud)
BTW的名称应该是Colors,不要colors尊重非常重要和非可选的Java命名约定.
您可以从字符串中获取枚举Enum.valueOf()。在这里要小心,其他答案没有提到Enum.valueOf()会抛出一个IllegalArgumentExceptionif 传递的字符串,该字符串不是枚举的有效成员。
确保正确格式化和缩进您的代码,它可以帮助我们(和您!)阅读并了解发生了什么:
// 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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们现在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!");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,该方法static现在是,并使用try-with-resources块在Scanner您完成后关闭它。