英文:
switch-case with a string and enum in java
问题
我想在Java中使用switch-case检查具有枚举值的字符串,所以我做了这样的操作:
public enum DemoEnumType {
ALL(""),
TOP("acb"),
BOTTOM("def");
private String code;
DemoEnumType(String code) {
this.code = code;
}
public String code() {
return this.code;
}
}
当我运行这段代码时,它会抛出一个异常:
public class Demo {
public static void main(String[] args) {
DemoEnumType typeValue = DemoEnumType.valueOf("acb");
switch (typeValue){
case ALL:
System.out.print("匹配");
case BOTTOM:
System.out.print("匹配");
case TOP:
System.out.print("匹配");
}
}
}
异常信息:
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant package.DemoEnumType.acb.
<details>
<summary>英文:</summary>
I wanted to check a string with the value of enum in java using switch-case, so I did like this:
public enum DemoEnumType {
ALL(""),
TOP("acb"),
BOTTOM("def");
private String code;
DemoEnumType(String code) {
this.code = code;
}
public String code() {
return this.code;
}
}
and when I run this code it throws an exception:
public class Demo {
public static void main(String[] args) {
DemoEnumType typeValue = DemoEnumType.valueOf("acb");
switch (typeValue){
case ALL:
System.out.print("match");
case BOTTOM:
System.out.print("match");
case TOP:
System.out.print("match");
}
}
}
**Exeption:**
>Exception in thread "main" java.lang.IllegalArgumentException: No enum constant package.DemoEnumType.acb.
</details>
# 答案1
**得分**: 2
```java
DemoEnumType typeValue = DemoEnumType.valueOf("acb");
没有具有值“acb”的枚举元素。如果没有具有给定名称的元素,Enum#valueOf
将抛出 IllegalArgumentException
。您需要使用 ALL
、BOTTOM
或 TOP
。
DemoEnumType type = DemoEnumType.valueOf("ALL");
或者,您可以使用一个 String 到 DemoEnumType 的 Map 进行 O(1) 查找,并使用您提供的值。
Map<String, DemoEnumType> valueToType = Stream.of(DemoEnumType.values())
.collect(Collectors.toMap(DemoEnumType::code, Function.identity()));
DemoEnumType type = valueToType.get("abc");
英文:
DemoEnumType typeValue = DemoEnumType.valueOf("acb");
No enum element exists with the value acb
. Enum#valueOf
will throw an IllegalArgumentException
if no element exists with the given name
. You need to use ALL
, BOTTOM
, or TOP
.
DemoEnumType type = DemoEnumType.valueOf("ALL");
Alternatively, you could use a Map of String to DemoEnumType for O(1) lookup and use the values you've provided.
Map<String, DemoEnumType> valueToType = Stream.of(DemoEnumType.values())
.collect(Collectors.toMap(DemoEnumType::code, Function.identity());
DemoEnumType type = valueToType.get("abc");
答案2
得分: 1
你的枚举成员是ALL、TOP和BOTTOM,而不是字符串值。你只能将它们传递给valueOf()方法。
要使用字符串值,你可以在枚举中创建一个方法,该方法接收一个字符串,并返回相应的枚举值。
英文:
Your Enum members are ALL, TOP and BOTTOM, not the string values. you can only pass then to valueOf().
To use the string values you can create a method in your Enum that receives a String and returns the appropriate Enum
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论