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 2.0 (Using type-safe generics)
 */
public class StatisticsCalculator
{
    private Vector<Double>        values;   // v2.0
    

    /**
     * Explicit Value Constructor
     *
     * @param name   The name of the file containing the sample
     */
    public StatisticsCalculator(String name) throws IOException
    {
       double        value;       
       Scanner       in;
    

       // Initialize the Vector
       values = new Vector<Double>();
       
       // Read the data
       in = new Scanner(new File(name));
       while (in.hasNext())
       {
          value = in.nextDouble();
          values.add(value);          // v2.0 (boxing)
       }
    }
    

    /**
     * Calculates the mean of a sample
     *
     * @return    The mean
     */
    public double mean()
    {
       double        total, value;
       

       total = 0.0;
       
       for (int i=0; i<values.size(); i++)
       {
          value =  values.elementAt(i);    // v2.0 (unboxing)
          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;

       mean  = mean();
       
       sum   = 0.0;
       
       for (int i=0; i<values.size(); i++)
       {
          value = values.elementAt(i);     // v2.0  (unboxing)
          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();       
    }
    
}
