我正在构建一个只使用 array的经典 Nim 游戏,我在测试后发现有一个错误。如果我成功创建了一个播放器,我会为数组分配一个新对象。但是,当删除数组中的播放器时,我会使用非空对象过滤数组,因为我还有其他函数,例如editplayer,displayplayer来迭代整个数组而没有NullPointerException.
并且有可能发生这种情况:addplayer→ removeplayer→ addplayer。这意味着IndexOutOfBound当我尝试将新对象分配给已经充满非空对象的数组时,我总是会得到。
我已经搜索了所有我能找到的信息,但是没有关于这个的讨论。有什么办法可以同时避免NullPointerException两者IndexOutOfBound?
这是相关代码Nimsys:
public class Nimsys {
public static void addPlayer(String [] name) {
if (name != null && name.length == 3) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exists.\n");// Test if player has been created
return;
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
return;
}
System.out.println("Not Valid! Please enter again!");
}
public static void searchAndRemovePlayer(String user) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);
return;
}
}
System.out.println("The player does not exist.\n");
}
}
这是NimPlayer课堂的一部分:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 10;
private static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public static void setPlayerList(NimPlayer [] newplayerList) {
playerList = Arrays.stream(newplayerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
counter = playerList.length; //update the counter
}
//setters and getters of the other variables
}