You see strings and characters at work in the
following program. This program differs from the one in
Segment 570 in two key ways. First, the program reads strings
from a file, as well as integers, and interprets the first character of
those strings as a code letter. Second, the program uses the code letter
to determine whether it should create a Movie
instance or a
Symphony
instance:
import java.io.*; import java.util.*; public class Demonstrate { public static void main(String argv[]) throws IOException { Vector mainVector; mainVector = Auxiliaries.readData("input.data"); for (Iterator i = mainVector.iterator(); i.hasNext();) { System.out.println(((Attraction)i.next()).rating()); } } }
import java.io.*; import java.util.*; public class Auxiliaries { public static Vector readData(String fileName) throws IOException { FileInputStream stream = new FileInputStream(fileName); InputStreamReader reader = new InputStreamReader(stream); StreamTokenizer tokens = new StreamTokenizer(reader); Vector v = new Vector(); while (tokens.nextToken() != tokens.TT_EOF) { String codeString = tokens.sval; tokens.nextToken(); int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; switch (codeString.charAt(0)) { // First character indicates a movie: case 'M': v.addElement(new Movie(x, y, z)); break; // First character indicates a symphony: case 'S': v.addElement(new Symphony(x, y, z)); break; } } stream.close(); return v; } }