// CSE 142, Autumn 2009, Marty Stepp // This program simulates the dropping of three balls from various heights. // It draws the balls on a DrawingPanel and animates using the sleep method. // The purpose of the program is to demonstrate return values // (the displacement method, and Math methods) and type double. // // This second version of the program uses Point objects to represent the // balls' x/y positions. This makes the code more concise and makes it // easier to add a 3rd ball. import java.awt.*; public class Balls2 { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(600, 600); panel.setBackground(Color.CYAN); Graphics g = panel.getGraphics(); Point ball1 = new Point(100, (600 - 600)); // height of 600 Point ball2 = new Point(200, (600 - 400)); // height of 400 Point ball3 = new Point(300, (600 - 500)); // height of 500 // draw the balls at each time increment for (double t = 0; t <= 10.0; t = t + 0.1) { drawBall(g, ball1, 25, t); // initial velocity of 25 drawBall(g, ball2, 0, t); // initial velocity of 0 drawBall(g, ball3, 15, t); // initial velocity of 15 panel.sleep(50); // pause for 50 ms } } // Draws the given ball point with the given initial velocity // after the given amount of time has elapsed. public static void drawBall(Graphics g, Point ball, double v0, double t) { double disp = displacement(v0, t, 9.81); int newY = ball.y + (int) disp; g.fillOval(ball.x, newY, 10, 10); } // Computes the displacement of a moving ball // with the given initial velocity, acceleration, and time. // displacement = v0 t + 1/2 a t^2 public static double displacement(double v0, double t, double a) { double d = v0 * t + 0.5 * a * Math.pow(t, 2); return d; } }