Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Yasir Khan
3,937 PointsHelp with a Java question for an exercise.
Hi I am doing this exercise of a Blue J book for my Java course and I am completely stumped on this question.
Basically I have to 1 Only the bounce method in BallDemo needs to be changed. 2 The number of balls should be made a parameter of the method. 3 The balls should be given random sizes and placed in a row at the top of the canvas.
This is the code so far, I am using an ArrayList to store the number of balls the user specifies. I do not want the answer, but would appreciate it if someone would explain to me how to do this.
public class BallDemo
{
private Canvas myCanvas;
private ArrayList<BouncingBall>balls;
private Random ballSize;
/**
* Create a BallDemo object. Creates a fresh canvas and makes it visible.
*/
public BallDemo()
{
myCanvas = new Canvas("Ball Demo", 600, 500);
balls = new ArrayList<BouncingBall>();
ballSize = new Random();
}
/**
* Simulate two bouncing balls
*/
public void bounce(BouncingBall ball)
{
int ground = 400; // position of the ground line
myCanvas.setVisible(true);
// draw the ground
myCanvas.drawLine(50, ground, 550, ground);
balls.add(ball);
//Trying to implement the method
// 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();
BouncingBall ball3 = new BouncingBall(90, 110, 24, Color.YELLOW, ground, myCanvas);
ball3.draw();
BouncingBall ball4 = new BouncingBall(110, 140, 28, Color.GREEN, ground, myCanvas);
ball4.draw();
// make them bounce
boolean finished = false;
while(!finished) {
myCanvas.wait(50); // small delay
ball.move();
ball2.move();
ball3.move();
ball4.move();
// stop once ball has travelled a certain distance on x axis
if(ball.getXPosition() >= 600 && ball2.getXPosition() >= 600 && ball3.getXPosition() >= 600
&& ball4.getXPosition() >= 600) {
finished = true;
}
}
}
}