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