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中将字符串与枚举类型进行比较?


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01