How to compare string to enum type in Java?(如何在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中将字符串与枚举类型进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在Java中将字符串与枚举类型进行比较?


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01