-1

I'm making a wheel of fortune game and i want to include a feature where the user enters in how many players there are and a constructor in a for loop makes that many players. I just don't know how I'd make the objects when they say how many players they want

Player constructor

public Player(String n) {
    money = 0.0;
    name = n;
}

Problem

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int playerAmount = 0;
    do {
        if(playerAmount > 5) System.out.println("Thats too many.");
        System.out.print("How many players(max 5): ");
        playerAmount = kb.nextInt();
    } while(playerAmount > 5 || playerAmount == 1);

    for(int i = 1; i <= playerAmount; i++) {
        System.out.print("Player " + i + " name: "); 
        String name = kb.next(); // name for the construction of player
        Player player1 = new Player(name); // where i want to construct differeing number of different objects
    }

}
  • You need array of object. – mazhar islam Oct 06 '16 at 23:40
  • Put it in a data structure like an array. `player1` is immediately lost after each iteration. – Andrew Li Oct 06 '16 at 23:40
  • Objects don't have names -- makes no sense. Variables do, but an object can be assigned to multiple variables, so say you have Player variables named Horace, Bill and Sharon, and all are assigned the same object, when then is the object's "name"? Again, it doesn't make sense. What matters is **references** and *properties*, the reference to get a way to access the object (perhaps an ArrayList or HashMap) and a String name property for the object's class, if you desire to associate a name with an object. – Hovercraft Full Of Eels Oct 07 '16 at 00:15

1 Answers1

0

The simple solution is to add each of the new players to a list:

List<Player> players = new ArrayList<>();
for (int i = 0; i < playerCount; i++) {
    players.add(new Player(kb.next()));
}

This might be a bit too complicated, but if you are using Java 8 you could also use a stream idiom for this:

List<Player> players = Stream.generate(kb::next)
    .map(Player::new).limit(playerCount).collect(Collectors.toList());

If you're not familiar with this, it means generate a stream of strings using kb.next(), convert them to players using new Player, limit the stream to the number of players you want then collect in a list.

sprinter
  • 27,148
  • 6
  • 47
  • 78