001package algs12; 002 003import stdlib.*; 004 005/* *********************************************************************** 006 * Compilation: javac Accumulator.java 007 * 008 * Mutable data type that calculates mean of data values. 009 * 010 *************************************************************************/ 011 012 013public class XAccumulator { 014 private double total; 015 private int N; 016 017 public void addDataValue(double val) { 018 N++; 019 total += val; 020 } 021 022 public double mean() { 023 return total / N; 024 } 025 026 public String toString() { 027 return "Mean (" + N + " values): " + String.format("%7.5f", mean()); 028 } 029 030 public static void main (String[] args) { 031 args = new String[] { "100" }; 032 int T = Integer.parseInt (args[0]); 033 XAccumulator a = new XAccumulator (); 034 for (int t = 0; t < T; t++) 035 a.addDataValue (StdRandom.random ()); 036 StdOut.println (a); 037 } 038}