// CSE 142, Autumn 2009, Marty Stepp // This program simulates the dropping of two 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. import java.awt.*; public class Balls { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(600, 600); panel.setBackground(Color.CYAN); Graphics g = panel.getGraphics(); int ball1x = 100; int ball1y = 600 - 600; // height of 600 int ball1v0 = 25; int ball2x = 200; int ball2y = 600 - 400; // height of 400 int ball2v0 = 0; // draw the balls at each time increment for (double t = 0; t <= 10.0; t = t + 0.1) { double disp1 = displacement(ball1v0, 9.81, t); g.fillOval(ball1x, ball1y + (int) disp1, 10, 10); double disp2 = displacement(ball2v0, 9.81, t); g.fillOval(ball2x, ball2y + (int) disp2, 10, 10); panel.sleep(50); // pause for 50 ms } } // 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 a, double t) { double result = v0 * t + 0.5 * a * Math.pow(t, 2); return result; } }