如何在Java中将字符串与枚举类型进行比较?

2022-01-25 00:00:00 string enums compare 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"

相关文章