我試圖在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
好吧,我這樣做,但玩家必須與名稱和雙手被實例化。我試過 (int i = 0; i
Allantir
@Allantir在初始化'players [i]'之前,您應該初始化'playerNames [i]'和'hands [i]'。 – Eran
現在看起來像這樣:'players = new Player [numberOfPlayers]; \t \t hands = new PlayerHand [players。長度]; \t \t對(INT I = 0; I
Allantir