我正在尝试使用用户输入的字符串作为类实例的名称。在此示例中,我尝试使用用户输入来命名类实例 player1
。但是,它不允许我这样做,因为当我将它设置为 players
类的实例时,已经定义了 player1
。
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();
最佳答案
在不指出明显的变量名称的情况下,我将采用不同的方法进行回答。
也许您想获取一个输入并以面向对象编程的方式将其实际设置为玩家
的名称。您显然有一个 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);
关于java - 如何将用户输入保存为类实例的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20929402/