MovingAverage.java


Below is the syntax highlighted version of MovingAverage.java from §1.5 Input and Output.


/******************************************************************************
 *  Compilation:  javac MovingAverage.java
 *  Execution:    java MovingAverage n < data.txt
 *  Dependencies: StdIn.java StdOut.java
 *
 *  This filter takes a moving average of the standard input stream
 *  and puts the result on standard output. There is no limit to
 *  the length of the streams.
 *
 *  % java MovingAverage 4
 *  2.0 4.0 6.0 2.0 2.0 2.0 2.0 3.0
 *  <ctrl-d>
 *  3.5 3.5 3.0 2.0 2.25
 *
 *  Note <Ctrl-d> signifies the end of file on OS X and Linux.
 *  On windows use <Ctrl-z>.
 *
 ******************************************************************************/

public class MovingAverage {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        double[] a = new double[n];
        double sum = 0.0;
        for (int i = 1; !StdIn.isEmpty(); i++) {
            sum -= a[i % n];
            a[i % n] = StdIn.readDouble();
            sum += a[i % n];
            if (i >= n) StdOut.print(sum/n + " ");
        }
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:14:17 EDT 2022.