Stewart Clay Stewart Clay - 2 months ago 5
Java Question

Is this way of searching an enum acceptable

i am busy with enum's and was looking at a way to search an enum to see if a string a user enters is there, so i created this.

enum Month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};

try {
String A = "DECc";
Month.valueOf(A);
} catch(Exception e) {
System.out.println("Could not find an enum with the String you entered");
}

Answer

yes this is good.. the other option is "to string" all the enum elements and compare the string to them one by one:

for (Month m : Month.values()) {
    if (m.name().equals(A)) {
        //found
    }
}

but your way is really better...

Comments