将枚举值更改为扫描仪输入的字符串? - Java

时间:2016-04-08 11:57:34

标签: java variables enums java.util.scanner

嗨,我想知道最好的办法是什么。基本上我有一个包含三个不同品牌名称的枚举类。在我创建的程序中,用户必须有一个选项来选择他们想要更改的品牌,并且能够输入字符串以将所选品牌更改为。

我不熟悉枚举操作以及我尝试的任何操作,例如创建一个名为userInput的变量,并尝试将枚举值分配给此我收到错误。

任何人都有任何想法?欢呼声

编辑:我的方法如下:

public void updateBrand(Scanner input) {

        boolean valid = false;
        int selection;
        System.out.println("The list of available brands are below:");
        System.out.println("1 - " + Brand.Highstreet);
        System.out.println("2 - " + Brand.TedBaker);
        System.out.println("3 - " + Brand.FrenchConnection);

        do {
            System.out.println("Please enter the number of the Brand you wish to change.");
            if (input.hasNextInt()) {
                selection = input.nextInt();
                if (selection < 1 || selection > 3) {
                    valid = false;
                    input.nextLine();
                System.out.println("Please enter a number betwen 1 and 3");
                } else
                    valid = true;
                    System.out.println("You have selected number: " + selection);
                    if (selection == 1) {
                        System.out.println("Please enter the changes you want to make to the brand :" + Brand.Highstreet);
                        System.out.println("New brand name : ");
                        String newBrand = input.nextLine();
                        Brand.Highstreet.????
                        //error on line above?? not sure what code to use.
                    }
            }

        } while (!valid);
    }

我的Enum课程:

package SuitProg;

public enum Brand {

    Highstreet,TedBaker,FrenchConnection;

    public String st;

    void Brand(String s){
        this.st = s;
    }

    void change(String newString) {
        this.st = newString;
    }

    String getContent() {
        return this.st;
    }

}

1 个答案:

答案 0 :(得分:1)

用于更改枚举值

的示例代码
class Test
{
    enum MyEnum
    {
        BRAND_1("A brand"),
        BRAND_2("A second brand"),
        BRAND_3("A third brand");

        private String st;

        MyEnum(String s)
        {
            this.st = s;
        }

        void change(String newString)
        {
            this.st = newString;
        }

        String getContent()
        {
            return this.st;
        }
    }

    public static void main(String...args)
    {
        MyEnum c1 = MyEnum.BRAND_2;

        c1.change("A magic brand!");

        System.out.println(MyEnum.BRAND_2.getContent());
    }
}

尽管如此,枚举被设计为表现为常量,因此您可以使用其他类型的结构来实现目的