如何在Java中初始化一个对象数组

我想初始化一个BlackJack游戏的Player对象数组。 我已经阅读了很多关于初始化原始对象的许多方法,比如一个int数组或者一个string数组,但是我不能把这个概念带到我想要做的事情(见下文)。 我想返回一个初始化的Player对象的数组。 玩家对象的数量是一个整数,我提示用户。 我正在考虑构造函数可以接受一个整数值,并相应地命名播放器,同时初始化Player对象的一些成员variables。 我觉得我很接近,但还是很困惑。

static class Player { private String Name; private int handValue; private boolean BlackJack; private TheCard[] Hand; public Player(int i) { if (i == 0) { this.Name = "Dealer"; } else { this.Name = "Player_" + String.valueOf(i); } this.handValue = 0; this.BlackJack = false; this.Hand = new TheCard[2]; } } private static Player[] InitializePlayers(int PlayerCount) { //The line below never completes after applying the suggested change Player[PlayerCount] thePlayers; for(int i = 0; i < PlayerCount + 1; i++) { thePlayers[i] = new Player(i); } return thePlayers; } 

编辑 – 更新:这是我得到后改变这个,因为我理解你的build议:

 Thread [main] (Suspended) ClassNotFoundException(Throwable).<init>(String, Throwable) line: 217 ClassNotFoundException(Exception).<init>(String, Throwable) line: not available ClassNotFoundException.<init>(String) line: not available URLClassLoader$1.run() line: not available AccessController.doPrivileged(PrivilegedExceptionAction<T>, AccessControlContext) line: not available [native method] Launcher$ExtClassLoader(URLClassLoader).findClass(String) line: not available Launcher$ExtClassLoader.findClass(String) line: not available Launcher$ExtClassLoader(ClassLoader).loadClass(String, boolean) line: not available Launcher$AppClassLoader(ClassLoader).loadClass(String, boolean) line: not available Launcher$AppClassLoader.loadClass(String, boolean) line: not available Launcher$AppClassLoader(ClassLoader).loadClass(String) line: not available BlackJackCardGame.InitializePlayers(int) line: 30 BlackJackCardGame.main(String[]) line: 249 

这几乎没有问题。 只要有:

 Player[] thePlayers = new Player[playerCount + 1]; 

让循环是:

 for(int i = 0; i < thePlayers.length; i++) 

请注意,Java约定规定方法和variables的名称应该以小写开头。

更新:把你的方法放在类体内。

代替

 Player[PlayerCount] thePlayers; 

你要

 Player[] thePlayers = new Player[PlayerCount]; 

 for(int i = 0; i < PlayerCount ; i++) { thePlayers[i] = new Player(i); } return thePlayers; 

应该返回用Player实例初始化的数组。

编辑:

请查看维基百科关于广泛使用的java命名约定的表格 。

如果你不确定数组的大小,或者如果它可以改变,你可以使用这个对话来有一个静态数组。

 ArrayList<Player> thePlayersList = new ArrayList<Player>(); thePlayersList.add(new Player(1)); thePlayersList.add(new Player(2)); . . //Some code here that changes the number of players eg Players[] thePlayers = thePlayersList.toArray(); 

初始化之后,数组不可更改。 你必须给它一个值,那个值就是数组的长度。 你可以创build多个数组来包含播放器信息的某些部分,比如他们的手等,然后创build一个arrayList来sorting这些数组。

我看到的另一个争论点,我可能是错误的是,你的私人播放器[] InitializePlayers()是静态的,现在类是非静态的。 所以:

 private Player[] InitializePlayers(int playerCount) { ... } 

我的最后一点是,你可能应该把playerCount声明在要改变它的方法之外,这样设置的值也成为新的值,并且不是在方法结尾抛弃“范围。”

希望这可以帮助

thePlayers[i] = new Player(i); 我只是删除了Player(i) ; 它的工作。

所以代码行应该是:

 thePlayers[i] = new Player9();