Java use user input to determine enum value

5.2k views Asked by At

I'm currently hardcoding an enum value, which is running through a switch statement. Is it possible to determine the enum based on user input.

Choice month = Choice.D;

Instead of hardcoding the value D, can I use the user input here?

package partyAffil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class partyAffil {

public static void main(String[] args) {
System.out.println("Choose from the following menu");
System.out.println("D, R, or I");   
String choice = getInput("please choose a letter.");


    Choice month = Choice.D;


    switch(month){ 
    case D:
        System.out.println("You get a Democratic Donkey");
        break;
    case R:
        System.out.println("You get a Republican Elephant");
        break;
    case I:
        System.out.println("You get an Independent Person");
        break;
    default:
        System.out.println("You get a unicorn");
        break;
        }
}

    public enum Choice{
        D, R, I;
    }

   private static String getInput(String prompt)
        {
        BufferedReader stdin = new BufferedReader(
                new InputStreamReader(System.in));
        System.out.print(prompt);
        System.out.flush();
        try{
            return stdin.readLine();
        } catch (Exception e){
            return "Error: " + e.getMessage();
        }
    }

}
3

There are 3 answers

0
Victor Dombrovsky On BEST ANSWER

Each enum constant have its own name as declared in its declaration. Static method valueOf of particular enum returns the enum constant of this type by name.


Thus, instead:

Choice month = Choice.D;

just use this:

Choice month = Choice.valueOf(choice);
0
NineToeNerd On

What if you create the switch on the input rather than the month (or both, if they must be implemented separately)?:

Choice month;


switch(choice.toUpperCase()){ 
case 'D':
    month = Choice.D
    System.out.println("You get a Democratic Donkey");
    break;
    ...
    }

Better yet, I believe you could even set the character values in the enum:

public enum Choice{
        D('D'), R('R'), I('I');
    }

This way, instead of case 'D': you can still use case D:

(Not sure about that one, I am more used to C-based languages)

0
VD007 On

Above given answers might help. If you are not an expert, use following code that will you understand the steps.

    public void run() throws Exception
{
        switch (menu() ) //calling a menu method to get user input.
        {
            case 1:
              //fyi, make sure you have all the methods in your code that is given for each menu choice.
              //you can have print statement in your method.
                  // e.g.       System.out.println("You get a Democratic Donkey");
                method1();
                break;
            case 2:
                method2();
                break;
            case 3:
                method3();
                break;      
            case 0:
                return;  
            //following default clause executes in case invalid input is received.
            default:
                System.out.println ( "Unrecognized option" );
                break;
            }
}

private int menu()
{   
    //list of menu items.
    System.out.println ("1. insert appropriate description for your menu choice 1.");
    System.out.println ("2. ");
    System.out.println ("3. ");
    System.out.println ("4. ");
    return IO_Support.getInteger(">>    Select Option: ", "Unrecognized option"); //you can use scanner to get user input. I have user separate class IO_Support that has getInteger methods to validate int user input. the text "unrecognized option" is what the message that i want to print if the option is integer but not valid choice.
}