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

查看:550
本文介绍了使用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);

这是我要获取的内容,但它不让我使用枚举颜色

This is what i'm trying to get but it's not letting me use the enum 'colors' in a switch statement.

推荐答案

在以下位置,您必须具有枚举类型的实例(其 member )您切换。您试图打开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) ...

BTW名称应为颜色,而不是颜色,以尊重非常重要且非可选的Java命名约定。

BTW the name should be Colors, not colors to respect the very important and non-optional Java naming convention.

这篇关于使用switch语句将字符串与枚举进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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