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

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

问题描述

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

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

将从包含状态的文本文件读取输入。因为它们是字符串,我如何将它与枚举列表的值进行比较,以便为我设置的变量赋值:

 私有状态; 



我理解我需要浏览枚举列表。但是,由于值不是字符串类型,你怎么比较呢?这是我只是盲目地输出。我不知道是否正确。

  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) ;
}

您可能想要处理IllegalArgumentException,不符合任何状态


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;
        }
    }
}

解决方案

try this

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

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

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

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