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 throw new BadDataException("Length expected");
44 int numberOfValues = in.nextInt();
45 data = new double[numberOfValues];
46
47 for (int i = 0; i < numberOfValues; i++)
48 readValue(in, i);
49
50 if (in.hasNext())
51 throw new BadDataException("End of file expected");
52 }
53
54 /**
55 Reads one data value.
56 @param in the scanner that scans the data
57 @param i the position of the value to read
58 */
59 private void readValue(Scanner in, int i) throws BadDataException
60 {
61 if (!in.hasNextDouble())
62 throw new BadDataException("Data value expected");
63 data[i] = in.nextDouble();
64 }
65 }