Use switch statement to compare a string against an enum(使用 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.
这篇关于使用 switch 语句将字符串与枚举进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 switch 语句将字符串与枚举进行比较


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01