go to previous page   go to home page   go to next page hear noise

Answer:

The finished program is given below.


Complete Program

The complete program can be copied and pasted into an editor, and run in the usual way.

import java.util.Scanner;

// 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 )  
  {
    final  double G = 9.80665;  // constant of gravitational acceleration
    int    t, limit;            // time in seconds; ending value of time
    double distance;            // the distance the brick has fallen
    Scanner scan = new Scanner( System.in );

    System.out.print( "Enter limit value: " );
    limit = scan.nextInt();

    // Print a table heading
    System.out.println( "seconds\tDistance"  );  // '\t' is tab
    System.out.println( "-------\t--------"  ); 

    t = 0 ;
    while (  t <= limit )    
    {
      distance = (G * t * t)/2 ;
      System.out.println( t + "\t" + distance );

      t = t + 1 ;
    }
  }
}

You could also write

distance = 0.5*G*t*t;

What were the two traps in translating the formula? If you translated it as (1/2)*G*t*t, you fell into the first trap. (1/2) asks for integer division of 1 by 2, resulting in zero.

If you translated the formula as 1/2*G*t*t, you fell into the second trap. 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.


QUESTION 17:

Now say that you want the table to show time increasing in steps of 0.1 seconds. Modify the program so that it does this with maximum accuracy. The user enters the limit in seconds.