// // Example of // - class with methods // - using arrays // - command line argument // - reading a file // - new for statement (see mean) // - Array.sort // - statistics // import java.io.*; import java.util.*; /** A data set of integers read from file, using ArrayList @author Patrick Prosser @ version 1.0 */ public class DataSet { private ArrayList data; private int n; /** create a data set from file, where file is an unknown number of numbers @param fname is the name of the file */ public DataSet(String fname) throws IOException { data = new ArrayList(); n = 0; Scanner sc = new Scanner(new File(fname)); while (sc.hasNext()){data.add(sc.nextInt());n++;} } public int size(){return data.size();} public String toString(){ String s = ""; for (int x : data) s = s + x + " "; return s; } public int mean(){ int sum = 0; for (int x : data) sum = sum + x; return sum/n; } public int min(){ int min = data.get(0); for (int x : data) min = Math.min(min,x); return min; } /** maximum in the data set */ public int max(){ int max = data.get(0); for (int x : data) max = Math.max(max,x); return max; } /** standard deviation */ public double stDev(){ int mean, sum, diff; mean = mean(); sum = diff = 0; for (int x : data){diff = x - mean; sum = sum + diff*diff;} return Math.sqrt((double)sum/(double)n); } /** gets file name from command line */ public static void main(String[] args) throws IOException { DataSet x = new DataSet(args[0]); System.out.println("n: "+ x.size() +" mean: "+ x.mean() +" min: "+ x.min() +" max: "+ x.max() +" stDev: "+ x.stDev()); //System.out.println(x); } }