0

In java i need to create dynamic bouncingBall. like this

BouncingBall bal
BouncingBall bal2
BouncingBall bal3

I'm trying to do this with a while loop:

// Create dynamich numbers of balls
int zero = 1;

while(zero < nrOfBalls)
{
    BouncingBall ball + zero = new BouncingBall(50, 50, 16, Color.BLUE, ground, myCanvas);
    ball.draw();
    zero++;
}

But is still saying that the +zero varbariable is not good. Could somebody help me!

@param nrOfBalls is the number what the users enters if nrOfBalls is 4 than the while loop must create 4 balls.

Bham
  • 309
  • 5
  • 21

1 Answers1

2

If you wish to have multiple BouncingBall variables, use an array.

BouncingBall[] balls = new BouncingBall[nrOfBalls];
int count = 0;
while(count< nrOfBalls)
{
    balls[count] = new BouncingBall(50, 50, 16, Color.BLUE, ground, myCanvas);
    balls[count].draw();
    count++;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Good solution, just extra info for poster: dynamic variable names do not exist in Java, and most of the time when you see yourself wanting to use these, either use an array (this is usually better and offers more functionality), or you should concider if you are trying to solve your problem in the right way. (since, if you think about it, using dynamic variable names is quite error prone, since you have no way of checking how many variables actually excist (edit: everything is ofcourse possible with reflection.. but lets not start on that :P)) – Pienterekaak Sep 03 '14 at 15:30