Get input from console for enum type

How do you get input from console for enum types in java?

I have this class:

class enumTest {

  public enum Color {
    RED, BLACK, BLUE
  }

  BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  Color color = input.readLine();

  public static void main (String[]args) {

  switch (color) {
    ...

On this line Color color = input.readLine(); i am getting an error which says:

incompatible types: String cannot be converted to Color

How do i get arround this?

Jon Skeet
people
quotationmark

Every enum has an automatically generated static valueOf method which parses a string. So you can use:

String colorName = input.readLine();
Color color = Color.valueOf(colorName);

However, this will throw an exception if the given name doesn't have any corresponding enum value. You may want to instead create a Map<String, Color> (either within Color or separately) so that you can handle this more elegantly.

people

See more on this question at Stackoverflow