The finished program is given below.
The complete program can be copied and pasted into NotePad, and run in the usual way.
import java.io.*; // User picks ending value for time, t. // The program calculates and prints the distance the brick has fallen for each t. // class fallingBrick { public static void main (String[] args ) throws IOException { final double G = 9.80665; // constant of gravitational acceleration int t, limit; // time in seconds, and ending value of time double distance; // the distance the brick has fallen BufferedReader userin = new BufferedReader (new InputStreamReader(System.in)); String inputData; System.out.println( "Enter limit value:" ); inputData = userin.readLine(); limit = Integer.parseInt( inputData ); // Print a table heading System.out.println( "seconds\tDistance" ); System.out.println( "-------\t--------" ); t = 0 ; while ( t <= limit ) { distance = (G * t * t)/2 ; System.out.println( t + "\t" + distance ); t = t + 1 ; } } } |
What were the two traps in translating the formula?
(1) If you translated it as (1/2)*G*t*t
, you are wrong.
This does integer division of 1 by 2, resulting in zero.
(2) If you translated it as 1/2*G*t*t
, you are wrong.
To the compiler,
this looks like the first wrong formula
(because "/" has equal precedence to "*").
A third problem is computing the square.
Do it as t
multiplied by t
.