1  import java.io.File;
  2  import java.io.IOException;
  3  import java.util.Scanner;
  4  
  5  /**
  6     Reads a data set from a file. The file must have the format
  7     numberOfValues
  8     value1
  9     value2
 10     . . .
 11  */
 12  public class DataSetReader
 13  {
 14     private double[] data;
 15  
 16     /**
 17        Reads a data set.
 18        @param filename the name of the file holding the data
 19        @return the data in the file
 20     */
 21     public double[] readFile(String filename) throws IOException
 22     {
 23        File inFile = new File(filename);
 24        Scanner in = new Scanner(inFile);
 25        try
 26        {
 27           readData(in);
 28           return data;
 29        }
 30        finally
 31        {
 32           in.close();
 33        }
 34     }
 35  
 36     /**
 37        Reads all data.
 38        @param in the scanner that scans the data
 39     */
 40     private void readData(Scanner in) throws BadDataException
 41     {
 42        if (!in.hasNextInt()) 
 43        {
 44           throw new BadDataException("Length expected");
 45        }
 46        int numberOfValues = in.nextInt();
 47        data = new double[numberOfValues];
 48  
 49        for (int i = 0; i < numberOfValues; i++)
 50        {
 51           readValue(in, i);
 52        }
 53  
 54        if (in.hasNext()) 
 55        {
 56           throw new BadDataException("End of file expected");
 57        }
 58     }
 59  
 60     /**
 61        Reads one data value.
 62        @param in the scanner that scans the data
 63        @param i the position of the value to read
 64     */
 65     private void readValue(Scanner in, int i) throws BadDataException
 66     {
 67        if (!in.hasNextDouble()) 
 68        {
 69           throw new BadDataException("Data value expected");
 70        }
 71        data[i] = in.nextDouble();      
 72     }
 73  }