我的java任务包括创建一个名为Qwixx的棋盘游戏。除了用于创建游戏的驱动程序类之外,还有四个类。在Qwixx类中,我需要创建一个构造函数,该构造函数具有String数组的参数,用于保存玩家的名称。
这是Qwixx类:
public class Qwixx {
private String[] Players;
//constructor
public Qwixx(String[] Players) {
for (int i = 0; i<Players.length; i++)
Players[i] = null; //here is my problem where I don't quite know how to
//fill this array with the names from the Driver
} //class
}
这是Driver类:
public class Driver {
public static void main(String[] args) {
Scanner myKey = new Scanner(System.in);
System.out.print("Please enter the number of players (2-5): ");
numPlayers = myKey.nextInt();
for (int i = 1; i<= numPlayers; i++) {
System.out.print("Please enter the name of player" + i + ": ");
String name = myKey.next();
Player joueur = new Player(); //for every player, an object must be
joueur.name = name; //created for the Player class
}
}
}
这是Player类:
public class Player {
public String name;
//default constructor
Public Player() {
name = null;
//initialization of other instance variables
}
//constructor
Public Player(String playerName) {
name = playerName; }
}
请帮我弄清楚如何将用户从Driver类输入的名称保存到Qwixx类的数组中。任何帮助表示赞赏!
答案 0 :(得分:-1)
public class Driver {
public static void main(String[] args) {
Scanner myKey = new Scanner(System.in);
System.out.print("Please enter the number of players (2-5): ");
int numPlayers = myKey.nextInt();
// Player joueur[]= new Player[numPlayers]; // Initializing the Player Objects
String playerNames[] = new String[numPlayers]; // String Array to store Player Names
for (int i = 0; i < numPlayers; i++) {
System.out.print("Please enter the name of player" + i + ": ");
String name = myKey.next();
// joueur[i].name = name; // Do you really need Player objects to do some other tasks? if yes uncomment this.
playerNames[i] = name;
}
Qwixx qwixx = new Qwixx(playerNames);
String testNames[] = qwixx.getPlayerNames();
for (String test : testNames) {
System.out.println(test);
}
// Some other code
}
}
class Qwixx {
private String[] Players;
public Qwixx() {
}
//constructor
public Qwixx(String[] Players) {
this.Players = new String[Players.length];
// System.arraycopy(Players, 0, this.Players, 0, Players.length);
// You can use this method System.arraycopy instead of the below for loop.
for (int i = 0; i < Players.length; i++) {
this.Players[i] = Players[i];
}
}
public String[] getPlayerNames() {
return this.Players;
}
}