954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

modifying all of the instances in an array at once

okay, here's the deal. I'm still quite fresh to programming. My task is to create a program, that can draw any number of balls, and then make them bounce across the canvas. The part of the task I am stuck on is converting convert a method that draws two balls to a canvass and makes them bounce, into a method that draws an number of balls and makes them bounce.

My problem, is that I can get any specified number of balls drawn, but I cant get them to all move at once..here is the code for just making two balls bounce:

----------------------------------------------------------------------public void bounce()
{
int ground = 400; // position of the ground line

myCanvas.setVisible(true);

// draw the ground
myCanvas.drawLine(50, ground, 550, ground);

// crate and show the balls
BouncingBall ball = new BouncingBall(50, 50, 16, Color.blue, ground, myCanvas);
ball.draw();
BouncingBall ball2 = new BouncingBall(70, 80, 20, Color.red, ground, myCanvas);
ball2.draw();

// make them bounce
boolean finished = false;
while(!finished) {
myCanvas.wait(50); // small delay
ball.move();
ball2.move();
// stop once ball has travelled a certain distance on x axis
if(ball.getXPosition() >= 550 && ball2.getXPosition() >= 550)
finished = true;
}
ball.erase();
ball2.erase();
}

this works fine...so far I have ammended the code to this....
----------------------------------------------------------------------
public void bounce(int numb)

{
int ball;
int ground = 400; // position of the ground line

myCanvas.setVisible(true);

// draw the ground
myCanvas.drawLine(50, ground, 550, ground);

// crate and show the balls
int xpos = 20;

allBalls = new BouncingBall[numb];
for (ball = 0; allBalls.length < numb; ball++)
{
allBalls[ball] = new BouncingBall(xpos, 20, 16, Color.blue, ground, myCanvas);
xpos = (xpos + 20);
allBalls[ball].draw();}
myCanvas.wait(50);

for (ball = 0; ball < numb; ball++)
{ allBalls[ball].move();


// make them bounce
while(allBalls[ball].getXPosition() >= 550)
{
allBalls[ball].erase();

}}
}
}


and the all I can get is nullpointer exception... I know that a null pointer is normally thrown when objects haven't been initialized, but this is twisting my melon a bit. I did have it drawing the blls, without moving them, but i started getting outofbounds exceptions so I messed with it a bit more, and now this. can somebody please help me? COming to a forum is a last resort after having spentabout a week on the projct as a whole, but then this one task has so far taken 2 days to try to figure out.

many thanks in advance

numballs
Newbie Poster
1 post since Dec 2003
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You