01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package algs12;

import stdlib.*;

/* ***********************************************************************
 *  Compilation:  javac Accumulator.java
 *
 *  Mutable data type that calculates mean of data values.
 *
 *************************************************************************/


public class XAccumulator {
  private double total;
  private int N;

  public void addDataValue(double val) {
    N++;
    total += val;
  }

  public double mean() {
    return total / N;
  }

  public String toString() {
    return "Mean (" + N + " values): " + String.format("%7.5f", mean());
  }

  public static void main (String[] args) {
    args = new String[] { "100" };
    int T = Integer.parseInt (args[0]);
    XAccumulator a = new XAccumulator ();
    for (int t = 0; t < T; t++)
      a.addDataValue (StdRandom.random ());
    StdOut.println (a);
  }
}