Java 使用switch语句将字符串与枚举进行比较
我正在用Java制作(我自己版本的)轮盘赌,玩家可以下的赌注之一就是选择要滚动的颜色。(偶数是黑色,奇数是红色)。有没有一种方法可以使用switch语句将字符串与枚举进行比较Java 使用switch语句将字符串与枚举进行比较,java,enums,switch-statement,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.
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语句中使用enum“colors”。您必须有一个enum类型(其成员)的实例,在该实例上进行切换。您正在尝试打开枚举类本身,这是一个无意义的构造。所以你可能需要
colors col = colors.valueOf(colorGuess);
switch (col) ...
顺便说一句,名称应该是
Colors
,而不是Colors
,以遵守非常重要且非可选的Java命名约定。您可以使用从字符串中获取枚举。注意,其他答案没有提到如果传递的字符串不是枚举的有效成员,则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
语句正如您所知,只要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!");
}
}
}
}
请注意,该方法现在是静态的,并且使用一个块来关闭扫描器。并且大小写必须是enum类名qualifiedNo,enum类名是隐含的。@Bohemian:事实上不是这样;在这种情况下,红色和黑色就可以了。非常感谢。已经为此使用了不必要的if/else if语句一段时间了,如果传递了OP试图处理的无效字符串,这将抛出一个IllegalArgumentException
。false:while(colorvify=false)
!!!我认为他试图在最后一行中说它应该是a==而不是a==并且他是正确的,while(!colorvify)
while(colorvify=false)甚至不会编译,因为它不返回布尔值!