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中将字符串与枚举类型进行比较?
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01