You can get an enum from a string with Enum.valueOf() . Take care that other answers do not mention that Enum.valueOf() will Enum.valueOf() IllegalArgumentException if a string is passed that is not a valid member of the enumeration.
Do not forget to format and deviate from the code correctly, it helps us (and you!) To read it and understand what is happening:
// note the capitalization, and the singular 'Color' private enum Color {RED, BLACK}; // At least with the code provided, you don't need colorGuess or colorVerify to be // instance variables, they can be local to the method. Limiting the amount of // time a variable lives for (its scope) is critical for quality, maintainable code public Color getColorGuess() { Scanner in = new Scanner(System.in); // this should be outside the while loop while(in.hasNextLine()) { // .toUpperCase() lets you type "red" or "RED" and still match String line = in.nextLine().toUpperCase(); try { // Enum.valueOf() throws an exception if the input is not valid Color guess = Color.valueOf(line); switch(guess) { case RED: return guess; // return, rather than break, to exit the method case BLACK: return guess; // As long as your switch statement covers all cases in your enum, you // don't need a default: case, you'll never reach it } } catch (IllegalArgumentException e) { System.out.println("Invalid color selection!"); } } }
Note that now we return guess in both cases, which is somewhat redundant. At least with the code example you provided, you actually do not need to track colorVerify at all, because the method will continue the loop forever until a valid color is entered. You can replace the entire switch in my method with a simple return guess; since you know this is a valid assumption as soon as Color.valueOf() returns a value.
In other words, you can clear your code to:
public static Color getColorGuess() { try (Scanner in = new Scanner(System.in)) { while(in.hasNextLine()) { try { return Color.valueOf(in.nextLine().toUpperCase()); } catch (IllegalArgumentException e) { System.out.println("Invalid color selection!"); } } } }
Note that the method is now static and uses the try-with-resources block to close the Scanner after you are "Done with it."
dimo414
source share