import java.io.*;
import java.util.*;

/**
 * A simple calculator that can be used to calculate
 * descriptive statistics from a sample contained in a file
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class StatisticsCalculator
{
    private ArrayList        values;
    

    /**
     * Explicit Value Constructor
     *
     * @param name   The name of the file containing the sample
     */
    public StatisticsCalculator(String name) throws IOException
    {
       double        value;       
       Double        wrappedValue;       
       Scanner       in;
    

       // Initialize the ArrayList
       values = new ArrayList();
       
       // Read the data
       in = new Scanner(new File(name));
       while (in.hasNext())
       {
          value        = in.nextDouble();
          System.out.println(value);
          
          wrappedValue = new Double(value);          
          values.add(wrappedValue);          
       }
    }
    

    /**
     * Calculates the mean of a sample
     *
     * @return    The mean
     */
    public double mean()
    {
       double        total, value;
       Double        wrappedValue;
       

       total = 0.0;
       
       for (int i=0; i<values.size(); i++)
       {
          wrappedValue = (Double)values.get(i);
          value        = wrappedValue.doubleValue();
          
          total +=     value;          
       }
       
       return total/((double)values.size());
    }
    

    /**
     * Calculates the sum of the squared residuals [i.e., the
     * sum of (x_i - xbar)^2 ]
     */
    private double ssr()
    {
       double        mean, sum, value;
       Double        wrappedValue;

       mean  = mean();
       
       sum   = 0.0;
       
       for (int i=0; i<values.size(); i++)
       {
          wrappedValue = (Double)values.get(i);
          value        = wrappedValue.doubleValue();
          
          sum += Math.pow((value - mean), 2);
       }
       
       return sum;
    }


    /**
     * Calculates the (biased) variance of a sample
     *
     * @return  The (biased) variance
     */
    public double variance()
    {
       return (1.0/(double)(values.size())) * ssr();       
    }
    
}
