使用 switch 语句将字符串与枚举进行比较 [英] Use switch statement to compare a string against an enum

查看:50
本文介绍了使用 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 语句将字符串与枚举进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆