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

2022-08-31 12:31:08

我想为二十一点游戏初始化一个 Player 对象数组。我已经阅读了很多关于初始化原始对象的各种方法,如int数组或字符串数组,但我无法将这个概念带到我在这里尝试做的事情(见下文)。我想返回初始化的播放器对象的数组。要创建的播放器对象的数量是一个整数,我提示用户输入该整数。我认为构造函数可以接受一个整数值,并在初始化 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  

答案 1

这几乎没问题。只需有:

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

并让循环是:

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

请注意,Java约定规定方法和变量的名称应以小写字母开头。

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


答案 2

而不是

Player[PlayerCount] thePlayers;

你想要

Player[] thePlayers = new Player[PlayerCount];

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

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

编辑:

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