Reading a file into an ArrayList

An ArrayList is also useful whenever you are reading input because you don't have to know in advance how many items there will be.

Instead of hard-coding the color and point data for the polylines as in the TestPlotter example, we would like to be able to read the data from a text file. Suppose that each line of the file corresponds to one polyline, and consists of the following:

A file may also contain blank lines, which should be ignored, and comments, which should be ignored. Any line starting with the pound sign character "#" is considered a comment.

For example, the text file describing the output from our test program could look like this (you can find it here too):

# draws a red square
red 100 100 200 100 200 200 100 200 100 100

# draws a blue triangle with line width of 2 pixels
2 blue 250 100 400 350 100 350 250 100

# draws a green zig-zag with a 6-pixel line
6 green 100 400 200 450 300 400 400 450

(Note: a simple way to tell whether a line is blank is to first use the String method trim(), which removes all leading and trailing whitespace, and then check whether the length is zero. To check whether there is an integer at the beginning of the line, just use the Scanner method hasNextInt().)

Checkpoint 3

Write a program that will read files of the above format and plot the polylines using the plotter. Start with a helper method that parses just one line and returns the corresponding Polyline object.
  private static Polyline parseOneLine(String line)
  {
  }

You can check whether it works with a short main method:

  public static void main(String[] args)
  {
    Plotter plotter = new Plotter();
    Polyline p = parseOneLine("red 100 100 200 100 200 200 100 200 100 100");
    plotter.plot(p);
    
    p = parseOneLine("2 blue 250 100 400 350 100 350 250 100");
    plotter.plot(p);
  }

Then, write a helper method that opens and reads the file, and returns an ArrayList of Polyline objects, one for each line (other than comments or blank lines). (You can refer to the sample code QuizAverager as a model for the file-reading loop.)

  private static ArrayList<Polyline> readFile(String filename)
      throws FileNotFoundException
  {
  }

Then the main method can iterate over the list, and call plot() for each Polyline. Try it on the file hello.txt.

  public static void main(String[] args) throws FileNotFoundException
  {
    ArrayList<Polylne> list = readFile("hello.txt");
    Plotter plotter = new Plotter();

    for (Polyline p : list)
    {
      plotter.plot(p);
    }
  }