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

82

我想为BlackJack游戏初始化一个Player对象的数组。我已经阅读了很多关于如何初始化原始对象(例如int数组或string数组)的方法,但是我无法将这个概念应用到我正在尝试做的事情上(请参见下文)。我想返回一个初始化的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类为什么是静态的?你能否尝试将其从中删除“static”关键字? - TheOtherGuy
好的 - 我尝试去掉“static”,编译器提示了以下内容:thePlayers[i] = new Player(i); - John Adams
类似这样的代码 http://pastie.org/1865618 应该可以编译。 - Bala R
https://www.tutorialcup.com/java/arrays-in-java.htm - Rahul Gupta
7个回答

100

这几乎是正确的。只需做出以下修改:

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

让循环如下:

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

需要注意的是,Java 的惯例要求方法和变量的名称应以小写字母开头。

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


1
我不确定你的意思。我在类Player中有一个构造函数。你是说将InitializePlayers也放到Player类中吗? - John Adams
1
@John Galt 是的。它不能在类外面。 - Bozho
@Powerlord 虽然它可能包含广泛使用的惯例并提供良好的建议,但我相信该文档中一半的项目过于晦涩,实际上不能被视为惯例。 - twiz
@twiz 公平地说,那份文档是 Oracle(前身为 Sun)要求其开发人员使用的编程规范。我还没有仔细研究过 OpenJDK 的代码,看看这些规范被遵循得如何。 - Powerlord
1
@Powerlord Java编程语言的代码规范是新(旧)的主页。 - user393219
你能解释一下为什么需要 +1 吗? - Lei Yang

23

而不是

Player[PlayerCount] thePlayers;

你想要

Player[] thePlayers = new Player[PlayerCount];

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

应该返回使用Player实例初始化的数组。
编辑:
请查看维基百科上的此表格,了解广泛使用的Java命名约定。

当您在循环中重新初始化thePlayers数组时,这不会创建内存泄漏吗? - user4748790

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();

1
我更喜欢使用 List<Player> thePlayersList = new ArrayList<Player>(); - Deqing
2
@Deqing 在这种情况下,我更喜欢使用 Object thePlayersList = new ArrayList<Player>(); - Joel Sjögren
@Deqing 在重载的情况下,实际上会以不同的方式运行。 - Neel

13
如果您能够硬编码玩家数量。
Player[] thePlayers = {
    new Player(0),
    new Player(1),
    new Player(2),
    new Player(3)
};

1

数组在初始化后不可更改。您需要给它一个值,该值就是数组长度所保持的值。您可以创建多个数组来包含玩家信息的某些部分,例如他们的手牌等,然后创建一个ArrayList来管理这些数组。

我看到另一个争议点,可能我错了,那就是您的私有Player[] InitializePlayers()是静态的,而类现在是非静态的。因此:

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

我的最后一点建议是,您应该在将要更改它的方法之外声明playerCount,以便设置为其值的值也成为新值,并且不仅在方法的“范围”结束时被丢弃。
希望这可以帮助您。

1
Player[] players = Stream.iterate(0, x-> x+1 ).limit(PlayerCount).map(i -> new Player(i)).toArray(Player[]::new);

0

thePlayers[i] = new Player(); 我刚刚删除了 Player(i) 中的 i;然后它就可以工作了。

所以代码行应该是:

thePlayers[i] = new Player9();

我认为这是因为他定义了玩家 public Player(int i),所以它应该最初接受一个整数输入。 - dexhunter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接