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

我想初始化一个BlackJack游戏的Player对象数组。我已经阅读了很多有关初始化原始对象(例如int数组或字符串数​​组)的各种方法的信息,但是我无法将此概念理解为我在此处尝试做的事情(见下文)。我想返回一个初始化的Player对象数组。要创建的播放器对象的数量是一个整数,我向用户提示。我以为构造函数可以接受一个整数值并在初始化Player对象的一些成员变量时相应地命名播放器。我想我很亲密,但仍然很困惑。

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;

}

编辑-更新: 这是我了解您的建议后所做的更改:

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约定规定方法和变量的名称应以小写字母开头。

更新:将您的方法放在类主体中。

以上是 如何在Java中初始化对象数组 的全部内容, 来源链接: utcz.com/qa/406718.html

回到顶部