如何将用户输入保存为类实例的名称?

时间:2014-01-05 02:42:31

标签: java class input

我正在尝试使用用户输入的字符串作为类实例的名称。在此示例中,我尝试使用用户输入来命名类实例player1。但是,它并没有让我这么做,因为当我将player1设置为players类的实例时,已经定义了System.out.println("Enter your name, player1: "); Scanner input = new Scanner(System.in); //the user enters their name String player1 = input.next(); players player1 = new players();

{{1}}

2 个答案:

答案 0 :(得分:5)

如果没有明确指出变量名称,我会采用不同的方法来回答。

也许您想要以OOP方式接受输入并实际将其设置为player的名称。你显然有一个类player,所以为什么不在构造函数中接受name参数?

public class Player {
    private String name;

    public Player(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

然后当你得到输入时你就这样做了

String playerName = input.nextLine();
Player player1 = new Player(playerName);

现在,当您创建多个Player时,每个人都会有一个不同的name


此外,您应该遵循Java命名约定。班级名称以大写字母开头


<强>更新

您需要为每个实例创建一个新的播放器

String playerName = input.nextLine();
Player player1 = new Player(playerName);

playerName = input.nextLine();
Player player2 = new Player(playerName);

playerName = input.nextLine();
Player player3 = new Player(playerName);

playerName = input.nextLine();
Player player4 = new Player(playerName);

答案 1 :(得分:1)

基本上你要做的就是选择一个有意义的变量名。就像在代数中一样,您不要将函数的输入用作变量名。但是,您确实将输入视为给定变量名称的替代。

您可以为player1选择更有意义的名称。也许如果您希望用户输入成为玩家的名字,那么player1字符串应该重命名为playerName,然后players player1 = new players();可以保留。

这是非典型的,通常表示设计不良,期望用户输入内容并定义您的变量名称。

相关问题