使用 switch 语句将字符串与枚举进行比较
我正在使用 Java 制作(我自己的版本)轮盘赌,玩家可以下注的一种类型是选择要滚动的颜色.(偶数为黑色,奇数为红色).有没有办法可以使用 switch 语句将字符串与枚举进行比较?
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?
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 语句中使用枚举颜色".
This is what i'm trying to get but it's not letting me use the enum 'colors' in a switch statement.
推荐答案
你必须有一个枚举类型的实例(它的成员)你可以在上面切换.您正在尝试打开 Enum 类本身,这是一个毫无意义的构造.所以你可能需要
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
colors col = colors.valueOf(colorGuess);
switch (col) ...
顺便说一句,名称应该是 Colors
,而不是 colors
,以尊重非常重要且非可选的 Java 命名约定.
BTW the name should be Colors
, not colors
to respect the very important and non-optional Java naming convention.
相关文章