Reading a file into an ArrayList
AnArrayList
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:
- An optional integer line width
- A color, which is a string such as "red" or "blue" (see the polyline javadoc for details on recognized colors)
- A sequence of integers representing coordinates of the points, where each pair is one point, x followed by y (there is always an even number of integers following the color name)
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 correspondingPolyline
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); } }