Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

for loop question

Question posted by: boomba (Newbie) on May 15th, 2008 12:40 PM
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("What is player 1's name?");
Player player = new Player(name);
player.enterWorld(world);
}
any suggestions ??? thankyou
Would you like to answer this question?
Sign up for a free account, or Login (if you're already a member).
JosAH's Avatar
JosAH
Chief Editor
6,993 Posts
May 15th, 2008
12:46 PM
#2

Re: for loop question
If I add a new second line like this:

Code: ( text )
  1. for (int i= 0; i < numPlayers; i++) {
  2.    ...
  3. }


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

kind regards,

Jos

Reply
boomba's Avatar
boomba
Newbie
5 Posts
May 15th, 2008
12:51 PM
#3

Re: for loop question
would i just fill out what i had before in the blanks

Reply
boomba's Avatar
boomba
Newbie
5 Posts
May 15th, 2008
01:08 PM
#4

Re: for loop question
Quote:
Originally Posted by JosAH
If I add a new second line like this:

Code: ( text )
  1. for (int i= 0; i < numPlayers; i++) {
  2.    ...
  3. }


... 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

Reply
JosAH's Avatar
JosAH
Chief Editor
6,993 Posts
May 15th, 2008
01:17 PM
#5

Re: for loop question
Quote:
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: ( text )
  1. Player[] player= new Player[n];


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

Reply
Reply
Not the answer you were looking for? Post your question . . .
174,849 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Top Java Forum Contributors