Reputation: 25
I am writing an interpreter that parses an array of String and assigns each word in that file a numeric value.
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.
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
No enum const class
Thanks in advance!
Upvotes: 2
Views: 1920
Reputation: 43867
The problem is that valueOf
throws an IllegalArgumentException
if the input is not a possible enum value. 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.
Upvotes: 3
Reputation: 10843
When there's no corresponding enum value, there will always be an IllegalArgumentException
thrown. 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]);
}
Upvotes: 11