Average.java


Below is the syntax highlighted version of Average.java from §2.4 Input and Output.


/*************************************************************************
 *  Compilation:  javac Average.java StdIn.java
 *  Execution:    java Average < data.txt
 *  
 *  Reads in a sequence of real numbers, and computes their average
 *  and standard deviation.
 *
 *  % java Average
 *  10.0 5.0 6.0
 *  3.0 7.0 32.0
 *  <Ctrl-d>
 *  Number  = 6
 *  Average = 10.5
 *  Standard deviation = 9.844626283748239

 *  Note <Ctrl-d> signifies the end of file on Unix.
 *  On windows use <Ctrl-z>.
 *
 *************************************************************************/

public class Average { 
   public static void main(String[] args) { 
      int n = 0;           // number input values
      double sum  = 0.0;   // sum of input values
      double sum2 = 0.0;   // sum of squares of input values

      // read data and compute statistics
      while(!StdIn.isEmpty()) {
         double x = StdIn.readDouble();
         n++;
         sum += x;
         sum2 += x*x;
      }

      double avg = sum / n;
      double stddev = Math.sqrt(sum2 / n - avg * avg);
      System.out.println("Number  = " + n);
      System.out.println("Average = " + avg);
      System.out.println("Standard deviation = " + stddev);
   }
}


Last updated: Wed Sep 22 10:23:44 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.