I'm trying to make a simple game in Java. In my main class, I let the player type in their names and how many players will be playing.
here is my code in the main class:
{...}
Board game = new Board (playerNames,numberOfPlayers);
game.run();
{...}
Now in my other class it looks like this:
private int numberOfPlayers;
private Player[] players = new Player[numberOfPlayers];
private String[] playerNames= new String[numberOfPlayers];
private PlayerHand[] hands = new PlayerHand[numberOfPlayers];
public Board(String[] s, int n) {
playerNames=s;
numberOfPlayers= n;
}
it then initializes the Players like this:
public void initializePlayer(){
for(int i=0;i<numberOfPlayers;i++){
hands[i]=new PlayerHand();
players[i]=new Player(playerNames[i],hands[i]);}
For testing I always set the numberOfPlayers directly in the Board class. Since I want to change it now that the ammount of players is not fixed anymore, I have a problem. I assume the problem is that the Arrays get initialized with 0, as numberOfPlayers is 0 at the beginning. How can I change this?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0