javaclasswhile-loopclass-constructors

how do you output a string and change that string


hello i am trying to create a specified amount of players in a game. I have looped the creation of players but everytime it loops it should go from making player1 to making player2 how do i construct a class which i defined in a separate file with that specific string ?

System.out.println("input starting monies in millions of dollaz");
double starterplayermoney = Double.valueOf(keyboard.nextLine());
System.out.println("input total players");
double doubletotalplayers = Double.valueOf(keyboard.nextLine()); 
int i = 1 ;
while(i<=doubletotalplayers){
    String playerstring = "player"+Integer.toString(i);
    player playerstring = new player();
    i++;    
}

Solution

  • You should use either an array or some collection of players. The thing is you are overwriting the reference to the player object in the next iteration here.

    player playerString = new player();
    

    Use an array like this:

    Player [] playerString = new Player [2];
    while( i <= doubletotalplayers){
    playerString[i] = new Player();
    

    }

    Also, I am not sure why would you need a double value for number of players. Try using int.