我想初始化一个BlackJack游戏的Player对象数组。我已经阅读了很多有关初始化原始对象(如整数数组或字符串数组)的各种方法的信息,但是我无法将其理解为我在此处尝试做的事情(见下文)。我想返回一个初始化的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
3 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
差不多了 只需:
Player[] thePlayers = new Player[playerCount + 1];
并让循环成为:
for(int i = 0; i < thePlayers.length; i++)
请注意,Java约定规定方法和变量的名称应以小写字母开头。
更新:将您的方法放在类主体中。
撒科打诨
TA贡献1934条经验 获得超2个赞
代替
Player[PlayerCount] thePlayers;
你要
Player[] thePlayers = new Player[PlayerCount];
和
for(int i = 0; i < PlayerCount ; i++)
{
thePlayers[i] = new Player(i);
}
return thePlayers;
应该返回用Player实例初始化的数组。
MM们
TA贡献1886条经验 获得超2个赞
如果不确定数组的大小或它是否可以更改,则可以使用静态数组。
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 e.g
Players[] thePlayers = thePlayersList.toArray();
添加回答
举报
0/150
提交
取消