Colorado State University

Recitation R9 - File Input & Output
Summer 2016

CS160: Foundations in Programming


The file

T 3 C 4 R 1
T 5 6
C 8.6
R 2.2 4
C 7.9
T 3.3 8.2
C 2.1
T 5.5 10.10
C 6.18
The first line of this file allocates the sizes for all the arrays.
The following lines represent the data for each object.
Since this file is in random order, so I'm going to have to be able to differentiate between shapes!

My readFile method for this file

	public void readFile(String inputFile) {
		// so that the Scanner has scope through the entire method
		// and not just in the try/catch block
		Scanner scan = null;
		try { // reading the file is a checked exception
			scan = new Scanner(new File(inputFile));
		} catch (FileNotFoundException e) {
			System.out.println("ERROR: Cannot open " + inputFile);
			System.exit(0);
		}

		// This loop grabs the first 6 items in pairs of 3
		for (int i = 0; i < 3; i++) {
			char shape = scan.next().charAt(0); // grab the character!
			int size = scan.nextInt(); // grabbing the size of the array
			// using a conditional statement to figure out which array I'm
			// allocating.
			if (shape == 'T') {
				tArray = new Triangle[size];
			} else if (shape == 'R') {
				rArray = new Rectangle[size];
			} else { // since it wasn't a 'T' or an 'R' it must be a 'C'
				cArray = new Circle[size];
			}
		}

		// Creating a counter because I need to know where to put each item in
		// my array!
		int tCount = 0, rCount = 0, cCount = 0;
		// How many obejcts am I looking for?
		int totalLines = tArray.length + rArray.length + cArray.length;
		for (int i = 0; i < totalLines; i++) {
			char type = scan.next().charAt(0);
			if (type == 'T') {
				Triangle t_temp = new Triangle(scan.nextDouble(), scan.nextDouble());
				tArray[tCount] = t_temp;
				tCount++;
			} else if (type == 'R') {
				Rectangle r_temp = new Rectangle(scan.nextDouble(), scan.nextDouble());
				rArray[rCount] = r_temp;
				rCount++;
			} else { // since it wasn't a 'T' or an 'R' it must be a 'C'
				Circle c_temp = new Circle(scan.nextDouble());
				cArray[cCount] = c_temp;
				cCount++;
			}
		}
	}


© 2015 CS160 Colorado State University. All Rights Reserved.