如何通过用户输入设置枚举的值

时间:2013-04-30 14:29:27

标签: java class enums

我正在尝试创建一个方法,通过该方法我可以返回用户输入设置的枚举值。我对一个枚举进行了decalred,然后我尝试通过用户输入来设置枚举。我无法使用我的GetPlayerClass方法返回Player_Class的值。有人可以告诉我,如果这是使用枚举设置值的正确方法,或者有一种方法可以让用户从枚举列表中选择并让我自己选择。

我的代码如下。

TLDR: 我是“enum dumb”,无法弄清楚如何从枚举中设置变量的值,然后再返回该值。请查看我的代码,让我知道我做错了什么。

  // The PCs base class
    private enum Base_Class {
        Barbarian, Bard, Cleric, Druid, Fighter, Monk, 
        Paladin, Ranger, Rogue, Sorcerer, Wizard
    };


 // Setting the base class
 public void setBaseClass() {
        do {
            System.out.println("Available Classes: ");
            System.out.println("Please select a cooresponding number for class.");
            int i = 1;
            for(Base_Class value: Base_Class.values()){
                System.out.println(i+": "+value.name());
                i++;
            }
            try {
                Base_Class_Choice = user_input.nextInt();
                switch(Base_Class_Choice) {
                    case 1:
                        Base_Class Player_Class;
                        Player_Class = Base_Class.Barbarian;
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                System.out.println("You must choose a valid class. Try numbers.");
                user_input.next();
            }
        } while (Base_Class_Choice == 0);
    }

    /**
     * Return my players class
     * @return
     */
    public String getPlayerClass() {
        return Player_Class;
    }

我更新了以下代码 我的尝试区域现在看起来像。

    try {
                Base_Class_Choice = user_input.nextInt();
                Base_Class Player_Class = Base_Class.values()[Base_Class_Choice - 1];
            } catch (Exception e) {
                System.out.println("You must choose a valid class. Try numbers.");
                user_input.next();
            }

但是Base_Class Player_Class的返回不起作用。

    public String getPlayerClass() {
        return Player_Class;
    }

当我尝试返回Player_Class时,它仍然失败,错误找不到符号。 我还能做错什么?

UPDATE !!!! “所有代码!!!”

/*
 * 
 * 
 */
package rpgmanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 *
 * @author Aaron
 */
public class Character {
        // The person playing the character
        private String Player_Name;
        // The PCs First Name
        private String First_Name;
        // The PCs Last Name
        private String Last_Name;
        // The PCs Race
        private enum Race {
            Dwarf, Halfling, Elf, Human, Gnome, HalfOrc, HalfElf
        };
        // The PCs base class
        private enum Base_Class {
            Barbarian, Bard, Cleric, Druid, Fighter, Monk, 
            Paladin, Ranger, Rogue, Sorcerer, Wizard
        };
        private Base_Class Player_Class;
        // Base Class Choice for switch case
        private int Base_Class_Choice = 0;
        // The PCs Height
        private int Height = 0;
        // The PCs Weight
        private int Weight = 0;
        // The PCs Age
        private int Age = 0;
        // The PCs base level
        private int Base_Level;
        // Sets up the scanner for inputs
        Scanner user_input = new Scanner(System.in);
        // Create a Buffered reader for input
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        // This instantiates a new character
        public Character() {

        }

        /**
         * Sets the PCs first name
         */
        public void setPlayerName() {
            System.out.print("Players Name: ");
            try {
                Player_Name = reader.readLine(); 
            } catch (IOException ioe) {
                System.out.println("The Player Name input failed to set.");
                System.out.println(ioe);
            }
        }

        /**
         * Sets the PCs first name
         */
        public void setFirstName() {
            System.out.print("First Name: ");
            try {
                First_Name = reader.readLine();
            } catch (IOException ioe) {
                System.out.println("The PCs First Name input failed to set.");
                System.out.println(ioe);
            }
        }

        /**
         * Sets the PCs last name
         */
        public void setLastName() {
            System.out.print("Last Name: ");
            try {
                Last_Name = reader.readLine();
            } catch (IOException ioe) {
                System.out.println("The PCs Last Name input failed to set.");
                System.out.println(ioe);
            }
        }

        /**
         * Sets the height of the PC
         */
        public void setHeight() {
            do {
                System.out.print("Height (inches): ");
                try {
                    Height = user_input.nextInt();
                    if(Height < 1) {
                        System.out.println("Not a valid number.");
                    }
                } catch(Exception e) {
                    System.out.println("You must use a number greater than 0!");
                    user_input.next();
                }
            } while (Height < 1);
        }

        /**
         * Sets the weight of the PC
         */
        public void setWeight() {
            do {
                System.out.print("Weight (pounds): ");
                try {
                    Weight = user_input.nextInt();
                    if (Weight < 1) {
                        System.out.println("Not a valid number.");
                    }
                } catch (Exception e) {
                    System.out.println("You must use a number greater than 0!");
                    user_input.next();
                }
            } while (Weight < 1);
        }

        /**
         * Sets the age of the PC
         */
        public void setAge() {
            do {
                System.out.print("Age (whole years): ");
                try {
                    Age = user_input.nextInt();
                    if (Age < 1) {
                        System.out.println("Not a valid number.");
                    }
                } catch (Exception e) {
                    System.out.println("You must use a number greater than 0!");
                    user_input.next();
                }
            } while (Age < 1);
        }

        /**
         * Sets the base level of the PC
         */
        public void setBaseLevel() {
            do {
                System.out.print("Starting Level: ");
                try {
                    Base_Level = user_input.nextInt();
                    if (Base_Level < 1 || Base_Level > 25) {
                        System.out.println("Not a valid number.");
                    }
                } catch (Exception e) {
                    System.out.println("You must choose a valid level between 1 and 25!");
                    user_input.next();
                }
            } while (Base_Level < 1 || Base_Level > 25);
        }

        public void setBaseClass() {
            do {
                System.out.println("Available Classes: ");
                System.out.println("Please select a cooresponding number for class.");
                int i = 1;
                for(Base_Class value: Base_Class.values()){
                    System.out.println(i+": "+value.name());
                    i++;
                }
                try {
                    Base_Class_Choice = user_input.nextInt();
                    Base_Class Player_Class = Base_Class.values()[Base_Class_Choice - 1];
                } catch (Exception e) {
                    System.out.println("You must choose a valid class. Try numbers.");
                    user_input.next();
                }
            } while (Base_Class_Choice == 0);
        }

        /**
        * Gets the PCs first name
        * @return 
        */
        public String getFirstName() {
            return First_Name;
        }

        /**
         * Gets the PCs last name
         * @return 
         */
        public String getLastName() {
            return Last_Name;
        }

        /**
         * Gets the PCs height
         * @return 
         */
        public int getHeight() {
            return Height;
        }

        /**
         * Gets the PCs age
         * @return 
         */
        public int getAge() {
            return Age;
        }

        /**
         * Gets the PCs base level (1-25)
         * @return
         */
        public int getBaseLevel() {
            return Base_Level;
        }

        /**
         * Gets the PCs player name
         * @return
         */
        public String getPlayerName() {
            return Player_Name;
        }

        /**
         *
         * @return
         */
        public Base_Class getPlayerClass() {
            return Player_Class;
        }

        /**
         *  Creates a new character
         */
        public void createCharacterNew() {
            this.setPlayerName();
            this.setFirstName();
            this.setLastName();
            this.setHeight();
            this.setWeight();
            this.setAge();
            this.setBaseLevel();
            this.setBaseClass();
        }
}

4 个答案:

答案 0 :(得分:1)

这应该工作(不需要开关块):

Player_Class = Base_Class.values()[Base_Class_Choice - 1];

答案 1 :(得分:1)

只要您在不同范围内声明和访问该变量(即两个函数),它就会继续失败。如果要在一个范围内分配它,并在另一个范围内访问它,则需要将其设置为包装类的成员变量。

您的问题具有误导性,因为您不想为用户输入分配枚举,您希望根据用户输入选择正确的枚举。

我为你提供了一个关于你原来问题的简化案例,在那里你可以看到我在谈论的是什么。

import java.util.Scanner;

class Player {
    private BaseClass playerClass;

    public void setPlayerClass() {
        Scanner in = new Scanner(System.in);
        StringBuilder output = new StringBuilder("Select a class:\n");
        BaseClass[] classes = BaseClass.values();
        for (int i = 0, len = classes.length; i < len; i++) {
            output.append("\t").append(i + 1).append(": ")
                  .append(classes[i].name()).append("\n");
        }
        output.append(" >> ");
        System.out.print(output.toString());
        int playerChoice = in.nextInt();
        in.close();
        switch (playerChoice) {
            case 1:
                playerClass = BaseClass.Barbarian;
                break;
            case 2:
                playerClass = BaseClass.Cleric;
                break;
            case 3:
                playerClass = BaseClass.Mage;
                break;
            case 4:
                playerClass = BaseClass.Fighter;
                break;
        }
    }

    public BaseClass getPlayerClass() {
        return playerClass;
    }

    public static void main(String[] args) {
        Player p = new Player();
        p.setPlayerClass();
        System.out.println("Player selected: " + p.getPlayerClass().name());
    }
}

enum BaseClass {
    Barbarian, Cleric, Mage, Fighter;
}

http://ideone.com/IZNykB

注意:为了进一步说明,您必须查看Java中变量的范围。变量的范围属于它定义的代码块。代码块包含在{}括号中的代码。由于您最初在交换机内部声明Player_Class,它属于交换机的范围,并且不存在于交换机的范围之外,因此访问它的方法没有返回您想要的内容。当您将Player_Class的声明移出开关,但仍在setPlayerClass内时,您所做的就是将其范围扩展到整个函数setPlayerClass,但setPlayerClass和{{1}不分享范围,因此你仍然没有得到你想要的结果。

在上面的例子中,我通过在名为getPlayerClass的{​​{1}}类上使用私有成员变量解决了这个问题,我可以分配并从类中的多个点返回,因为变量的作用域是我创建的Player类的实例。

答案 2 :(得分:0)

这不是您使用enum的方式。枚举是固定的,无状态的对象,你永远不会实例化(这就是为什么它们的构造函数是私有的,因为编译器为你做了。

另外,在旁边 - 使用大写字母表示类名,小写表示字段和方法。此外,使用camelCase,而不是underscore_case - 大多数Java程序员都会这样做,并且这样做会使您更容易阅读其他代码并让其他人阅读您的代码。

我会将BaseClass放入一个单独的文件中,以便您可以在任何地方使用它。然后使用方便的values()数组。我将如何做到这一点:

BaseClass.java

public enum BaseClass {
    BAR ("Barbarian"), BRD ("Bard"), CLR ("Cleric"), DRU ("Druid"),
    FGT ("Fighter"), MON ("Monk"), PAL ("Paladin"), RAN ("Ranger"),
    ROG ("Rogue"), SOR ("Sorceror"), WIZ ("Wizard");

    private String fullName;
    private BaseClass(String fullName) { this.fullName = fullName; }

    public String getFullName() {
        return fullName;
    }
    // Here you can add other useful methods
};

Player.java

// snip

public void setBaseClass() {
    do {
        System.out.println("Available Classes: ");
        System.out.println("Please select a cooresponding number for class.");
        int i = 1;
        for(BaseClass value: BaseClass.values()){
            System.out.println(i+": "+value.name());
            i++;
        }
        try {
            int baseClassChoice = user_input.nextInt();
            if (i < 1 || i >= BaseClass.values()) {
                System.out.println("That is not a valid choice. Please try again");
                continue;
            }
            Player_Class = BaseClass.values()[i-1];
        } catch (Exception e) {
            System.out.println("You must choose a valid class. Try numbers.");
            user_input.next();
        }
    } while (Base_Class_Choice == 0);
}

答案 3 :(得分:0)

您可以使用类似于以下示例代码的内容。它在我的环境中正常运行,你可以尝试自己。

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

enum BaseClass {
    Barbarian(1), Bard(2), Cleric(3), Druid(4), Fighter(5), Monk(6), Paladin(7), Ranger(8), Rogue(9), Sorcerer(10), Wizard(11);

    private int numericValue;
    private static final Map<Integer, BaseClass> intToEnum = new HashMap<Integer, BaseClass>();
    static {
        for (BaseClass type : values()) {
            intToEnum.put(type.getNumericValue(), type);
        }
    }

    private BaseClass(int numericValue)
    {
        this.numericValue = numericValue;
    }

    public int getNumericValue()
    {
        return this.numericValue;
    }

    public static BaseClass fromInteger(int numericValue)
    {
        return intToEnum.get(numericValue);
    }
};

public class Game {
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(System.in);
        BaseClass choice;

        do {
            System.out.println("Available Classes: ");
            System.out.println("Please select a cooresponding number for class.");

            for (Base_Class value : Base_Class.values()) {
                System.out.println(value.getNumericValue() + " : " + value);
            }

            choice = BaseClass.fromInteger(input.nextInt());
            if (choice == null) {
                System.out.println("Please select a valid class");
            }
        } while (choice == null);

        System.out.println("Successfully chosen: " + choice);
        input.close();
    }
}