我是一名java初学者,我尝试将播放器添加到数组中。我以为我成功地解决了这个问题,但事实并非如此。我已完成以下操作:
- 我发送了一条分割文本来创建播放器。
- 我在 NimPlayer 中创建了一个构造函数。
- 我在 Nimsys 中设置了数组来保存创建的玩家数据。
我有两个问题:
- 数组一开始肯定是全空的。如果我在这里使用唯一的数组,是否可以在此处添加播放器?
- 我已经设置了用于记录创建的播放器的
计数器
,但我无法在 else 语句中执行此操作。
这是我的代码:
int static counter;
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name; }
public static void main(String[] args) {
NimPlayer[] playerList = new NimPlayer[10]; // set an array here
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
//Can use playerCheck to simplify the code
if (name != null && name.length==3 && counter < 10) {
if (playerList != null) {
for (int i = 0; i < playerList.length; i++) {
String userCheck = playerList[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist.");
} else {
System.out.println("The player has been created.");
playerList[counter++] = new NimPlayer(name[0],name[1],name[2], 0, 0);
}
}
} else {
// I have to add the player here
}
} else {
System.out.println("Invalid input! e.g. addplayer george,Washington,George");
}
}
我的 NimPlayer 是:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
public NimPlayer(String userName, String familyName, String givenName, int gamePlayed, int score) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamePlayed = gamePlayed;
this.score = score;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
public int setScore(int score) {
return score;
}
public int getScore() {
return score;
}
public int setGamePlayed (int gamePlayed) {
return gamePlayed;
}
public int getGamePlayed() {
return gamePlayed;
}
}
最佳答案
- 是的,您可以根据需要更改数组元素。因此,“添加”玩家(在数组边界内设置数组元素的值)是可以的。
- else(“//我必须在此处添加玩家”)永远不会到达,因为
playerList
永远不会为空。
由于playerList中的所有元素都初始化为null,因此在调用之前应该检查playerList[i]
是否为null
getUserName()
(以避免 NullpointerException)。
关于java - 如何通过检查现有数组在空数组中添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61335871/