How to initialize an array of objects in Java
Asked Answered
B

7

82

I want to initialize an array of Player objects for a BlackJack game. I've read a lot about various ways to initialize primitive objects like an array of ints or an array of strings but I cannot take the concept to what I am trying to do here (see below). I would like to return an array of initialized Player objects. The number of player objects to create is an integer for which I prompt the user. I was thinking the constructor could accept an integer value and name the player accordingly while initializing some member variables of the Player object. I think I am close but still quite confused too.

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;
}

EDIT - UPDATE: Here is what I am getting after changing this as I understood your suggestion:

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  
Banerjee answered 4/5, 2011 at 19:46 Comment(3)
is there a reason whey Player class is static? can you maybe try removing static keyword from it?Benumb
OK - I tried removing "static" and compiler flagged the following: thePlayers[i] = new Player(i);Banerjee
Something like this pastie.org/1865618 should compile.Cracy
L
100

It is almost fine. Just have:

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

And let the loop be:

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

And note that java convention dictates that names of methods and variables should start with lower-case.

Update: put your method within the class body.

Leolaleoline answered 4/5, 2011 at 19:48 Comment(6)
Not sure what you mean here. I have constructor inside class Player. Do you mean put InitializePlayers inside Player class too?Banerjee
@John Galt yes. It cannot be outside the classLeolaleoline
@Tearing Although it might contain the widely used conventions and provide good suggestions, I'm pretty sure half the items in that document are way too obscure to actually be considered conventions.Between
@Between To be fair, that document is the programming conventions Oracle née Sun has its own developers use. I haven't gone through the code to OpenJDK to see how well they were followed.Tearing
@Tearing Code Conventions for the Java Programming Language is the new (old) home.Feign
could you explain why need +1?Hijack
C
23

Instead of

Player[PlayerCount] thePlayers;

you want

Player[] thePlayers = new Player[PlayerCount];

and

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

should return the array initialized with Player instances.

EDIT:

Do check out this table on wikipedia on naming conventions for java that is widely used.

Cracy answered 4/5, 2011 at 19:48 Comment(1)
Won't this create memory leaks when your re-initialize the thePlayers array is the loop?Cryptomeria
K
14

If you are unsure of the size of the array or if it can change you can do this to have a static array.

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();
Kazmirci answered 15/6, 2011 at 14:35 Comment(3)
I'd prefer List<Player> thePlayersList = new ArrayList<Player>(); Atalayah
@Atalayah In that case I'd prefer Object thePlayersList = new ArrayList<Player>();.Corwun
@Atalayah That will actually run differently in the case of overloading.Garvey
L
13

If you can hard-code the number of players

Player[] thePlayers = {
    new Player(0),
    new Player(1),
    new Player(2),
    new Player(3)
};
Looby answered 31/3, 2020 at 20:34 Comment(0)
L
1

Arrays are not changeable after initialization. You have to give it a value, and that value is what that array length stays. You can create multiple arrays to contain certain parts of player information like their hand and such, and then create an arrayList to sort of shepherd those arrays.

Another point of contention I see, and I may be wrong about this, is the fact that your private Player[] InitializePlayers() is static where the class is now non-static. So:

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

My last point would be that you should probably have playerCount declared outside of the method that is going to change it so that the value that is set to it becomes the new value as well and it is not just tossed away at the end of the method's "scope."

Hope this helps

Latashialatch answered 18/4, 2013 at 14:19 Comment(0)
C
1
Player[] players = Stream.iterate(0, x-> x+1 ).limit(PlayerCount).map(i -> new Player(i)).toArray(Player[]::new);
Chaille answered 24/3, 2020 at 22:27 Comment(0)
S
0

thePlayers[i] = new Player(i); I just deleted the i inside Player(i); and it worked.

so the code line should be:

thePlayers[i] = new Player9();
Schneider answered 2/7, 2015 at 7:36 Comment(1)
I think it's because the way he defined player public Player(int i) So it should take an integer input initially.Leishaleishmania

© 2022 - 2024 — McMap. All rights reserved.