I am a beginner and I am building a classical Nim game. So far, I've made the functions of adding and removing players. Now, I want to display the players, but bumped into this ArrayIndexOutOfBoundsException
. I've checked this article, but couldn't find what's wrong with my code. For-Each Loop Java Error ArrayIndexOutOfBoundsException
Basically, I grab the information using getters from NimPlayer
, and I use each loop to print out players. I've checked the loop's length, but it doesn't work.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Nimsys.processCommands(Nimsys.java:35) at Nimsys.main(Nimsys.java:12)
- line 12 refers to
processCommands
. - line 35 is the
displayPlayer()
function inprocessCommands
.
非常感谢您的帮助,感谢您的友好和耐心。
Here is part of my Nimsys
:
public class Nimsys {
private NimModel nimModel;
public static void main(String[] args) {
Nimsys nimsys = new Nimsys();
nimsys.processCommands();
}
Scanner in = new Scanner(System.in);
private void processCommands() {
this.nimModel = new NimModel();
System.out.println("Welcome to Nim\n");
while (true) {
System.out.print('$');
String [] commandin = in.nextLine().split(" ");
if (commandin[0].equalsIgnoreCase("displayplayer")) {
displayPlayer(commandin[1]);
}
}
private void displayPlayer(String userName) {
if (!userName.isEmpty()) {
nimModel.displayCertainPlayer(userName);
return;
} else {
nimModel.displayAllPlayers();
return;
}
}
part of my NimModel
:
public void displayCertainPlayer(String inputUser) {
if (inputUser != null && playerList.size() != 0 ) {
for (NimPlayer player : playerList) {
String userCheck = player.getUserName();
String userName = player.getUserName();
String familyName = player.getFamilyName();
String givenName= player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
if (userCheck.equals(userName)) {
System.out.println(userName + "," + familyName + "," + givenName + "," + gamesPlayed + " games," + gamesWon + " wins");
} else {
System.out.println("The player does not exist");
}
}
}
}
public void displayAllPlayers() {
if (playerList.size() != 0) {
for (NimPlayer player : playerList) {
String userName = player.getUserName();
String familyName = player.getFamilyName();
String givenName= player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
System.out.println(userName + "," + familyName + "," + givenName + "," + gamesPlayed + " games," + gamesWon + " wins");
}
} else {
System.out.println("There is no players.");
}
}
part of NimPlayer
:
ublic class NimPlayer {
private final String userName;
private String familyName;
private String givenName;
private int gamesPlayed;
private int gamesWon;
private int winRatio;
public NimPlayer(String userName, String familyName, String givenName) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamesPlayed = 0;
this.gamesWon = 0;
}
// getters and setters
}