[英]Processing strings not matched by Java enum
I am writing an interpreter that parses an array of String and assigns each word in that file a numeric value. 我正在编写一个解析器来解析一个String数组,并为该文件中的每个单词分配一个数值。
What I want to accomplish, is this: 我想要完成的是这样的:
If the word is not found in the enum, call an external method parse()
for that particular element of the array. 如果在枚举中找不到该单词,则为该数组的特定元素调用外部方法
parse()
。
My code looks similar to this: 我的代码看起来类似于:
private enum Codes {keyword0, keyword1};
switch Codes.valueOf(stringArray[0])
{
case keyword0:
{
value = 0;
break;
}
case keyword1:
{
value = 1;
break;
}
default:
{
value = parse(StringArray[0]);
break;
}
}
Unfortunately, when this finds something that does not equal "keyword0" or "keyword1" in the input, I get 不幸的是,当它在输入中找到不等于“keyword0”或“keyword1”的东西时,我得到了
No enum const class
没有枚举const类
Thanks in advance! 提前致谢!
When there's no corresponding enum value, there will always be an IllegalArgumentException
thrown. 当没有相应的枚举值时,将始终抛出
IllegalArgumentException
。 Just catch this, and you're good. 抓住这个,你很好。
try {
switch(Codes.valueOf(stringArray[0])) {
case keyword0:
value = 0;
break;
case keyword1:
value = 1;
break;
}
}
catch(IllegalArgumentException e) {
value = parse(stringArray[0]);
}
The problem is that valueOf
throws an IllegalArgumentException
if the input is not a possible enum value. 问题是如果输入不是可能的枚举值,
valueOf
会抛出IllegalArgumentException
。 One way you might approach this is... 你可能采取的一种方法是......
Codes codes = null;
try {
Codes codes = Codes.valueOf(stringArray[0]);
} catch (IllegalArgumentException ex) {
}
if(codes == null) {
value = parse(StringArray[0]);
} else {
switch(codes) {
...
}
}
If you're doing heavy duty parsing you may also want to look into a full fledged parser like ANTLR too. 如果你正在进行重度解析,你也可能想要像ANTLR那样研究一个完整的解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.