for loop question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • boomba
    New Member
    • Apr 2008
    • 5

    for loop question

    im trying to modify this code using a "for" loop to create 'numPlayers' players. That is, if the user types in 3 for 'numPlayers', then it should loop 3 times and create 3 players.

    private void readPlayers()
    {

    int numPlayers = askForInt("How many players will play?");
    String name = askForString("W hat is player 1's name?");
    Player player = new Player(name);
    player.enterWor ld(world);
    }
    any suggestions ??? thankyou
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    If I add a new second line like this:

    [code=java]
    for (int i= 0; i < numPlayers; i++) {
    ...
    }
    [/code]

    ... you only have to fill in the blanks and probably create a Player array before
    the loop starts.

    kind regards,

    Jos

    Comment

    • boomba
      New Member
      • Apr 2008
      • 5

      #3
      would i just fill out what i had before in the blanks

      Comment

      • boomba
        New Member
        • Apr 2008
        • 5

        #4
        Originally posted by JosAH
        If I add a new second line like this:

        [code=java]
        for (int i= 0; i < numPlayers; i++) {
        ...
        }
        [/code]

        ... you only have to fill in the blanks and probably create a Player array before
        the loop starts.

        kind regards,

        Jos
        i get a .class error saying .class expected

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by boomba
          i get a .class error saying .class expected
          If you get a compilation error or a runtime error you can't figure out yourself post
          the complete error message and the relevant code that caused the error. You
          can't expect from us to be psychic or own chrystal balls. btw, when you submit
          code look at the little legenda to the right of the edit window. Enclose your code
          in those code tags for readability reasons.

          If you want 'n' players you can define an array with 'n' elements:

          [code=java]
          Player[] player= new Player[n];
          [/code]

          next you have to create each of those n players just as you created that single
          player. Obviously you can and have to do that in a simple loop; each pass through
          that loop creates another Player.

          kind regards,

          Jos

          Comment

          Working...