如何通过用户输入设置枚举值 [英] How to set the value of an enum by user input

查看:153
本文介绍了如何通过用户输入设置枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to create a method by which I can return the value of an enum set by the users input. I decalred an enum, then I try to set the enum by the users input. I am unable to use my GetPlayerClass method to return the value of Player_Class. Can someone please tell me if this is the correct way to use an enum to set a value or is there a way I can allow the user to select from the enum list and let me get their choice.

我的代码在下面。

TLDR:
我是enum dumb,不知道如何设置值从一个枚举的变量,然后返回该值。请查看我的代码,让我知道我在做错什么。

TLDR: I am "enum dumb" and can't figure out how to set the value of a variable from an enum and then return that value later. Please view my code and let me know what I am doing wrong.

  // 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;
    }

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

I updated the code below My try area now looks like so.

    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的返回值不起作用。

But the return for the Base_Class Player_Class does not work.

    public String getPlayerClass() {
        return Player_Class;
    }

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

When I try to return Player_Class it still fails out with the error cannot find symbol. What could I still be doing wrong?

更新!!!! 所有的代码!!!

UPDATE!!!! "ALL THE CODE!!!"

/*
 * 
 * 
 */
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();
        }
}


推荐答案

只要您在不同范围(即两个功能)中声明和访问该变量,将继续失败。如果你想在一个范围内分配它,并在另一个范围内访问它,你将需要使它成为一个包装类的成员变量。

It's going to continue to fail as long as you are declaring and accessing that variable in different scopes (i.e. two functions). If you want to assign it in one scope, and access it in another you are going to need to make it a member variable of a wrapping class.

你的问题是误导的,因为您不想分配用户输入的枚举,您希望根据用户输入选择适当的枚举。

Your question is misleading, because you don't want to assign an enum the users input, you want to select the proper enum based on user input.

我为您提供了一个简化的案例原创问题在ideone,你可以看到我在说什么在行动。

I offer you a simplified case of your original problem in ideone where you can see what I'm talking about in action.

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 getPlayerClass 不共享范围,因此您仍然没有得到您正在寻找的结果。

NOTE: To further clarify, you have to watch where you scope variables in Java. The scope the variable belongs to the block of code in which it defined. A block of code being code wrapped in {} braces. Since you originally declared Player_Class inside of a switch, it belonged to the scope of the switch and did not exist outside of it, hence why the method that accessed it didn't return what you wanted it to. When you moved the declaration of Player_Class out of the switch, but still inside of setPlayerClass all you did was scope it to the entire function setPlayerClass but setPlayerClass and getPlayerClass do not share scope and therefore you were still not getting the result you were looking for.

在我上面的例子中,我通过在<$ c上使用一个私有成员变量来解决这个问题$ c> Player class $ code> playerClass 我可以从类中的多个点分配和返回,因为该变量的作用域是我创建的实例玩家类。

In my above example I've solved this by using a private member variable on the Player class called playerClass that I can assign and return from multiple points within the class because the variable is scoped to the instance I created of the Player class.

这篇关于如何通过用户输入设置枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆