Java使用用户输入来确定枚举值

时间:2015-06-10 03:33:53

标签: java enums

我目前正在对枚举值进行硬编码,该值通过switch语句运行。是否可以根据用户输入确定枚举。

let

我可以在这里使用用户输入而不是硬编码值Choice month = Choice.D; 吗?

D

3 个答案:

答案 0 :(得分:2)

每个枚举常量都有自己的名称,如声明中所声明的那样。特定枚举的静态方法valueOf按名称返回此类型的枚举常量。

因此,相反:

Choice month = Choice.D;

只需使用:

Choice month = Choice.valueOf(choice);

答案 1 :(得分:0)

如果您在输入而不是月份(或两者都必须单独实施)上创建开关,该怎么办?:

Choice month;


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

更好的是,我相信你甚至可以在枚举中设置字符值:

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

这样,您仍然可以使用case 'D':

代替case D:

(不确定那个,我更习惯基于C语言)

答案 2 :(得分:0)

以上给出的答案可能有所帮助。 如果您不是专家,请使用以下代码来了解这些步骤。

    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.
}