Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to initialize an array of objects in Java
    text
    copied!<p>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.</p> <pre><code>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 &lt; PlayerCount + 1; i++) { thePlayers[i] = new Player(i); } return thePlayers; } </code></pre> <p><strong><em>EDIT - UPDATE:</em></strong> Here is what I am getting after changing this as I understood your suggestion:</p> <pre><code>Thread [main] (Suspended) ClassNotFoundException(Throwable).&lt;init&gt;(String, Throwable) line: 217 ClassNotFoundException(Exception).&lt;init&gt;(String, Throwable) line: not available ClassNotFoundException.&lt;init&gt;(String) line: not available URLClassLoader$1.run() line: not available AccessController.doPrivileged(PrivilegedExceptionAction&lt;T&gt;, 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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload