Joh*_*ams 71 java arrays initialization object
我想为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;
}
Run Code Online (Sandbox Code Playgroud)
编辑 - 更新: 这是我改变这一点后得到的,因为我理解你的建议:
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
Run Code Online (Sandbox Code Playgroud)
Boz*_*zho 91
几乎没问题.只要:
Player[] thePlayers = new Player[playerCount + 1];
Run Code Online (Sandbox Code Playgroud)
让循环为:
for(int i = 0; i < thePlayers.length; i++)
Run Code Online (Sandbox Code Playgroud)
请注意,java约定规定方法和变量的名称应以小写字母开头.
更新:将您的方法放在类体中.
Bal*_*a R 21
代替
Player[PlayerCount] thePlayers;
Run Code Online (Sandbox Code Playgroud)
你要
Player[] thePlayers = new Player[PlayerCount];
Run Code Online (Sandbox Code Playgroud)
和
for(int i = 0; i < PlayerCount ; i++)
{
thePlayers[i] = new Player(i);
}
return thePlayers;
Run Code Online (Sandbox Code Playgroud)
应返回使用Player实例初始化的数组.
编辑:
Ugu*_*mru 14
如果您不确定数组的大小或是否可以更改,则可以执行此操作以获得静态数组.
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();
Run Code Online (Sandbox Code Playgroud)
Joh*_*kel 11
If you can hard-code the number of players
Player[] thePlayers = {
new Player(0),
new Player(1),
new Player(2),
new Player(3)
};
Run Code Online (Sandbox Code Playgroud)