Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27255

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?

Upvotes: 1

Views: 3986

Answers (2)

swojtasiak
swojtasiak

Reputation: 606

Store read line in String variable and then use valueOf method of the Enum class in order to convert string into enum instance.

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502835

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.

Upvotes: 6

Related Questions