//----------------------------------------------------------------------------- // 2/24/200 TYan and DIS // bouncing balls // Use methods //----------------------------------------------------------------------------- class Ball { // Instance Variables char name; double pos; double vel; // THOUGHT1: How to set values of instance variables // when instantiating the objects? See constructors. // Instance Method void updatemotion(double dt, double accel) { pos += vel*dt + accel*dt*dt/2.0; vel += accel*dt; if (pos <= 0.0) vel = -vel; } // method updatemotion // THOUGHT2: how to make accel and dt available to all objects? // See static and final for ideas. } // class Ball //----------------------------------------------------------------------------- // balls --not Ball!-- is the target class for the main method //----------------------------------------------------------------------------- public class balls_methods { public static void main(String[] args) { // Allocate and assign 3 ball objects a, b, c Ball a = new Ball(); Ball b = new Ball(); Ball c = new Ball(); // Initial Values double accel = -0.2; a.name = '*'; a.pos = 15.0; a.vel = 4.0; b.name = '+'; b.pos = 28.0; b.vel = .5; c.name = '#'; c.pos = 3.0; c.vel = -2.0; // Repeatedly move and draw balls for limit time units // Each loop is a time step lasting dt time units double limit = 100.0; // total time for simulation double time = 0.0; // elapsed time double dt = 1.0; // length of each time step while (time < limit) { // Sort Balls a.pos <= b.pos <= c.pos Ball tmp; if (a.pos > b.pos) { tmp = a; a = b; b = tmp; } if (b.pos > c.pos) { tmp = b; b = c; c = tmp; } if (a.pos > b.pos) { tmp = a; a = b; b = tmp; } // Print balls int i; // next column to draw in current row for (i = 0; i < (int) a.pos; i++) System.out.print(" "); if (0 <= (int) a.pos) { System.out.print(a.name); i++; } for ( ; i < (int) b.pos; i++) System.out.print(" "); if ((int) a.pos < (int) b.pos) { System.out.print(b.name); i++; } for ( ; i < c.pos; i++) System.out.print(" "); if ((int) b.pos < (int) c.pos) { System.out.print(c.name); i++; } System.out.println(); // advance to next line for (i = 0; i<1e6; i++) ; // delay // Move balls -- bounce elastically with the ground a.updatemotion(dt, accel); b.updatemotion(dt, accel); c.updatemotion(dt, accel); // Update elapsed time time += dt; } } // method main } // class balls_methods