如何在Java中将字符串与枚举类型进行比较? [英] How to compare string to enum type in Java?

查看:60
本文介绍了如何在Java中将字符串与枚举类型进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个美国所有州的枚举列表,如下所示:

I have an enum list of all the states in the US as following:

public enum State
{ AL, AK, AZ, AR, ..., WY }

在我的测试文件中,我将从包含状态的文本文件中读取输入.由于它们是字符串,我如何将其与枚举列表的值进行比较,以便将值分配给我设置为的变量:

and in my test file, I will read input from a text file that contain the state. Since they are string, how can I compare it to the value of enum list in order to assign value to the variable that I have set up as:

private State state;

我知道我需要检查枚举列表.但是,由于这些值不是字符串类型,如何比较呢?这就是我盲目输入的内容.不知道对不对.

I understand that I need to go through the enum list. However, since the values are not string type, how can you compare it? This is what I just type out blindly. I don't know if it's correct or not.

public void setState(String s)
{
    for (State st : State.values())
    {
        if (s == State.values().toString())
        {
           s = State.valueOf();
           break;
        }
    }
}

推荐答案

试试这个

public void setState(String s){
 state = State.valueOf(s);
}

如果s"值与任何State"都不匹配,您可能想要处理可能引发的 IllegalArgumentException

You might want to handle the IllegalArgumentException that may be thrown if "s" value doesn't match any "State"

这篇关于如何在Java中将字符串与枚举类型进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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