Java在对象创建中使用参数创建数组

时间:2016-12-01 13:52:31

标签: java arrays class object

我试图用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]);}

为了测试我总是直接在Board类中设置numberOfPlayers。既然我想改变它,现在玩家的数量不再固定,我就有问题了。我假设问题是Arrays初始化为0,因为numberOfPlayers在开始时为0。我怎么能改变这个?

  

线程中的异常&#34; main&#34; java.lang.ArrayIndexOutOfBoundsException:0

3 个答案:

答案 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];
}

答案 1 :(得分:1)

该行

if

等于

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

因为实例字段初始化为默认值(private String[] playerNames = new String[0]; 0)。

您应该将所有初始化内容移动到将知道数组大小的控制器。此外,在数组初始化之后不需要保留一些播放器(int)(n将返回相同的内容):

players.length

答案 2 :(得分: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];
}