简体   繁体   中英

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.

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!

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]);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM