2016-12-01 110 views
3

我試圖在Java中製作一個簡單的遊戲。在我的主要課程中,我讓玩家鍵入他們的名字以及將玩多少玩家。Java在創建對象時創建數組參數

,這裏是我的主類代碼:

{...} 
Board game = new Board (playerNames,numberOfPlayers); 
     game.run(); 
{...} 

現在,在我的其他類,它看起來是這樣的:

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; 
    } 

它然後初始化喜歡本作的玩家:

public void initializePlayer(){  
     for(int i=0;i<numberOfPlayers;i++){ 
      hands[i]=new PlayerHand(); 
      players[i]=new Player(playerNames[i],hands[i]);} 

爲了測試,我總是將numberOfPlayers直接設置在Board類中。由於現在我想改變它的玩家數量不再是固定的,我有一個問題。我認爲問題在於數組初始化爲0,因爲numberOfPlayers在開始時爲0。我該如何改變這一點?

異常線程「main」 java.lang.ArrayIndexOutOfBoundsException:0

回答

3

實例化陣列,同時numberOfPlayers仍含有0它的默認值,所以它們都是空數組。

你應該實例化它們的構造。

public Board(String[] s, int n) { 
    playerNames=s; 
    numberOfPlayers= n; 
    players = new Player[numberOfPlayers]; 
    playerNames= new String[numberOfPlayers]; 
    hands = new PlayerHand[numberOfPlayers]; 
} 
+0

好吧,我這樣做,但玩家必須與名稱和雙手被實例化。我試過 (int i = 0; i Allantir

+0

@Allantir在初始化'players [i]'之前,您應該初始化'playerNames [i]'和'hands [i]'。 – Eran

+0

現在看起來像這樣:'players = new Player [numberOfPlayers]; \t \t hands = new PlayerHand [players。長度]; \t \t對(INT I = 0; I Allantir

1

private String[] playerNames = new String[numberOfPlayers]; 

因爲一個實例字段具有缺省值(0int)初始化等於

private String[] playerNames = new String[0]; 

您應該將所有初始化的東西移動到一個控制器,其中數組的大小將被知道。此外,也沒有必要保持一些玩家(n)陣列初始化後(players.length將返回相同):

public Board(String[] s, int n) { 
    ... 
    players = new Player[n]; 
} 
+0

這可能是最漂亮的解決方案,我會這樣做 – Allantir

1

當您創建的陣列,它們的大小爲0,因爲numOfPlayers在這一點上是0 。
您需要創建初始化它們在構造函數後您指定的玩家數的值

private int numberOfPlayers; 
private Player[] players; 
private String[] playerNames; 
private PlayerHand[] hands; 
public Board(String[] s, int n) { 
    playerNames=s; 
    numberOfPlayers= n; 
    players = new Player[numberOfPlayers]; 
    playerNames= new String[numberOfPlayers]; 
    hands = new PlayerHand[numberOfPlayers]; 
}