Andrew Andrew - 28 days ago 17
Java Question

Java: Double not being calculated inside loop

I am trying to move a projectile every 10 milliseconds using an animation loop in a separate class. The first two iterations of this loop print that gravity is equal to 0 when it should only be able to zero on the first loop since time = 0 at the start.

public static void move()
{
System.out.println( "Time: " + time );
System.out.println( "gravity: " + gravity );
System.out.println( "g: " + g );
dX = Slingshot.getPullX();
dY = Slingshot.getPullY();
gravity = 0.5 * g * time * time;
newX = (double) Slingshot.getStart().x + time * c * dX;
newY = (double) Slingshot.getStart().y + ( time * c * dY + gravity );
time = time + 1;

new Projectile( newX, newY, dX, dY );
trail = new Ellipse( ( int ) newX + 5, ( int ) newY + 5 );
trail.setColor( Color.RED );
trail.setSize( 2, 2 );
projectileTrail.add( trail );
}


Here is the output after a few iterations of the loop:

Time: 0.0
gravity: 0.0
g: 2.0
Time: 1.0
gravity: 0.0
g: 2.0
Time: 2.0
gravity: 1.0
g: 2.0
Time: 3.0
gravity: 4.0
g: 2.0
Time: 4.0
gravity: 9.0
g: 2.0
Time: 5.0
gravity: 16.0
g: 2.0

Answer

You are printing the results before you have calculated them, so the 2nd loop is showing what you calculated in the first.

Just move your printlns to the end of the loop.

Comments