问题描述
我有一个美国所有州的枚举列表如下:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!