Contents

  1. ./ConsoleIODemo.java
  2. ./DataIODemo.java
  3. ./FileTest2.java
  4. ./InvoiceUsingText.java
  5. ./PetSurvey2.java
  6. ./PetSurvey.java

./ConsoleIODemo.java 1/6

[
top][prev][next]
package examples;

import java.util.Scanner;

/**
 * A program that shows reading in from the console and doing arithmetic.
 * 
 * @author Sara Sprenkle
 */
public class ConsoleIODemo {

	/**
	 * @param args
	 *            not used in this program
	 */
	public static void main(String[] args) {
		System.out.println("Test Program");

		// open the Scanner on the console input, System.in
		Scanner scan = new Scanner(System.in);
		scan.useDelimiter("\n"); // breaks up stream by lines, useful for console I/O


		String widthPrompt = "Please enter the width of a rectangle (as an integer): ";
		System.out.print(widthPrompt);
		// check for bad input
		while (!scan.hasNextInt()) {
			handleBadInput(scan, widthPrompt);
		}
		int width = scan.nextInt();

		String heightPrompt = "Please enter the height of a rectangle (as an integer): ";
		System.out.print(heightPrompt);

		// check for bad input
		while (!scan.hasNextInt()) {
			handleBadInput(scan, heightPrompt);
		}
		int length = scan.nextInt();
		scan.close();

		System.out
				.println("The area of your square is " + length * width + ".");
	}


	/**
	 * When the user enters bad input, remove the rest of what's on the line
	 * from the scanner and print out an error message and a reminder of what
	 * the input should look like.
	 * 
	 * @param scan
	 *            where the bad input is coming from
	 * @param prompt
	 *            a reminder of what we're looking for
	 */
	public static void handleBadInput(Scanner scan, String prompt) {
		// read the bad input (up to the \n, which is what the user
		// entered to trigger reading the input)
		scan.nextLine();

		// give an error message, repeating what we want
		System.out.println("Incorrect input.");
		System.out.println(prompt);
	}


}

./DataIODemo.java 2/6

[
top][prev][next]
package examples;

import java.io.*;

/**
 * Demonstrate use of DataInput/OutputStreams with merchandise invoices.
 * 
 */
public class DataIODemo {
	
	/**
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		// I know I don't want this variable to change within this method, so
		// made it final
		final String FILENAME = "invoice.dat";

		// stream to write the data out
		DataOutputStream out = new DataOutputStream(new FileOutputStream(
				FILENAME));

		double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
		int[] units = { 12, 8, 13, 29, 50 };
		String[] descs = { "Java T-shirt", "Java Mug", "Java Beach Towel",
				"Java Pin", "Java Key Chain" };

		// write the data out
		for (int i = 0; i < prices.length; i++) {
			out.writeDouble(prices[i]);
			out.writeChar('\t');
			out.writeInt(units[i]);
			out.writeChar('\t');
			out.writeChars(descs[i]);
			out.writeChar('\n');
		}
		out.close();

		// read the data in again
		DataInputStream in = new DataInputStream(new FileInputStream(FILENAME));

		double price;
		int unit;
		StringBuffer desc;
		double total = 0.0;

		final String lineSepString = System.getProperty("line.separator");
		char lineSep = lineSepString.charAt(0);

		while (in.available() > 0) {
			price = in.readDouble();
			in.readChar(); // throws out the tab
			unit = in.readInt();
			in.readChar(); // throws out the tab
			char chr;
			desc = new StringBuffer(20);
			while ((chr = in.readChar()) != lineSep)
				desc.append(chr);
			System.out.println("You've ordered " + unit + " units of " + desc
					+ " at $" + price);

			total = total + unit * price;
		}
		in.close();

		// 1.5+ way
		System.out.printf("For a TOTAL of $%10.2f\n", total);
		// OR
		System.out.format("For a TOTAL of $%.2f", total);
	}
}

./FileTest2.java 3/6

[
top][prev][next]
package examples;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Demonstrate using File objects and FileInputStreams in Java.
 * 
 * @author Sara Sprenkle
 * 
 */
public class FileTest2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String basedir = "/Users/sprenkle/Documents/cs209_workspace/09-exceptions_and_files";
		// create a file that represents the current directory
		File f = new File(basedir + File.separator + "chicken.data");
		System.out.println("File is " + f.getAbsolutePath());
		try {
			FileInputStream fin = new FileInputStream(f);
			while (fin.available() > 0) {
				System.out.println(fin.read());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

./InvoiceUsingText.java 4/6

[
top][prev][next]
package examples;

import java.io.*;
import java.util.Scanner;

/**
 * Demonstrate use of PrintWriter/Scanner with merchandise invoices.
 * 
 */
public class InvoiceUsingText {

	public static void main(String[] args) throws IOException {

		final String FILENAME = "invoice.dat";

		// write the data out
		PrintWriter out = new PrintWriter(FILENAME);

		double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
		int[] units = { 12, 8, 13, 29, 50 };
		String[] descs = { "Java T-shirt", "Java Mug", "Java Beach Towel",
				"Java Pin", "Java Key Chain" };

		for (int i = 0; i < prices.length; i++) {
			out.print(prices[i]);
			out.print('\t');
			out.print(units[i]);
			out.print('\t');
			out.println(descs[i]);
		}
		out.close();

		// read it in again
		Scanner in = new Scanner(new FileReader(FILENAME));

		double price;
		int unit;
		String desc;
		double total = 0.0;

		while (in.hasNext()) {
			price = in.nextDouble();
			unit = in.nextInt();
			in.skip("\t"); // eat tab
			desc = in.nextLine();
			System.out.println("You've ordered " + unit + " units of " + desc
					+ " at $" + price);
			total = total + unit * price;
		}
		in.close();

		// 1.5+ way
		System.out.printf("For a TOTAL of $%10.2f\n", total);
		// OR
		System.out.format("For a TOTAL of $%.2f", total);
	}
}

./PetSurvey2.java 5/6

[
top][prev][next]
package examples;

import java.io.*;
import java.util.Scanner;

/**
 * This class represents a pet survey, keeping track of the number of votes cast
 * for a set of pets. The results are stored in a file.
 * 
 * This version uses a PrintWriter instead of a FileWriter
 * 
 * @author CS209
 * 
 */
public class PetSurvey2 {

	private String filename;
	private String[] animals = { "dog", "cat", "bird", "fish", "snake", "other" };
	private int[] votes = new int[animals.length];
	private int totalVotes = 0;

	public PetSurvey2(String fn) {
		this.filename = fn;
		importResults();
	}

	/**
	 * Read the survey data from the file
	 */
	private void importResults() {
		try {
			BufferedReader input = new BufferedReader(new FileReader(filename));

			String line;
			int i = 0;
			while ((line = input.readLine()) != null) {
				// System.out.println(line);
				String data[] = line.split(" ");

				String animal = data[0];
				int thisVotes = Integer.parseInt(data[1]);

				animals[i] = animal;
				votes[i] = thisVotes;
				i++;
				totalVotes += thisVotes;
			}

			input.close();
		} catch (FileNotFoundException e) {
			System.out.println(filename
					+ ", containing the survey results, not found");
			e.printStackTrace();
		} catch (IOException e) {
			System.out
					.println("Something went wrong while importing survey results from"
							+ filename);
			e.printStackTrace();
		}

	}

	/**
	 * Store the current voting results into the file. Note the format of the
	 * input file.
	 * 
	 * @throws FileNotFoundException
	 */
	public void storeResults() throws FileNotFoundException {
		PrintWriter out = new PrintWriter(filename);
		// loop through the animals
		for (int i = 0; i < animals.length; i++) {
			// write out the animal, space, votes on separate lines
			out.print(animals[i]);
			out.print(" ");
			out.print(votes[i]);
			out.print("\n");
		}
		out.close();
	}

	/**
	 * 
	 * @return the name of the file containing the survey results
	 */
	public String getFilename() {
		return filename;
	}

	/**
	 * 
	 * @return the array of Strings of animal names in the survey
	 */
	public String[] getAnimals() {
		return animals;
	}

	/**
	 * 
	 * @return the array of integers, representing the number of votes for each
	 *         animal.
	 */
	public int[] getVotes() {
		return votes;
	}

	/**
	 * 
	 * @return the number of votes that have been cast.
	 */
	public int getTotalVotes() {
		return totalVotes;
	}

	/**
	 * Casts a vote for the animal
	 * 
	 * @param animal
	 *            -- must be a valid animal
	 */
	public void castVote(String animal) {
		for (int i = 0; i < animals.length; i++) {
			if (animals[i].equals(animal)) {
				votes[i]++;
				totalVotes++;
				return;
			}
		}
	}

	/**
	 * 
	 * @param animal
	 * @return true iff the animal is a valid animal
	 */
	public boolean validAnimal(String animal) {
		for (int i = 0; i < animals.length; i++) {
			if (animals[i].equals(animal)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Display the results from the survey in a nicely formatted way.
	 */
	public void displayResults() {
		System.out.println("Animal\tVotes\tPercentage");
		for (int i = 0; i < animals.length; i++) {
			double pct = (double) votes[i] / totalVotes * 100;
			System.out.printf("%-6s%7d%12.2f%%\n", animals[i], votes[i], pct);
		}
	}

	/**
	 * @param args
	 *            not used in this program.
	 */
	public static void main(String[] args) {
		final String mySurveyFile = "petSurvey.dat";
		PetSurvey2 survey = new PetSurvey2(mySurveyFile);

		System.out.println("Current Results: ");
		survey.displayResults();

		// Allow User to Vote
		Scanner scanner = new Scanner(System.in);
		System.out
				.print("What animal do you want to vote for as your favorite? (dog, cat, bird, snake, fish, other): ");

		String animalVoted = scanner.nextLine();

		if (!survey.validAnimal(animalVoted)) {
			System.out.println("I'm sorry.  " + animalVoted
					+ " is not a valid selection.");
			System.out.println("Check your spelling or select other.");
		} else {
			survey.castVote(animalVoted);
		}

		// Display updated results
		System.out.println("Updated Results: ");
		survey.displayResults();

		try {
			survey.storeResults();
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

}

./PetSurvey.java 6/6

[
top][prev][next]
package examples;

import java.io.*;
import java.util.Scanner;

/**
 * This class represents a pet survey, keeping track of the number of votes cast
 * for a set of pets. The results are stored in a file.
 * 
 * This version uses a FileWriter
 * 
 * @author CS209
 * 
 */
public class PetSurvey {

	private String filename;
	private String[] animals = { "dog", "cat", "bird", "fish", "snake", "other" };
	private int[] votes = new int[animals.length];
	private int totalVotes = 0;

	public PetSurvey(String fn) {
		this.filename = fn;
		importResults();
	}

	/**
	 * Read the survey data from the file
	 */
	private void importResults() {
		try {
			BufferedReader input = new BufferedReader(new FileReader(filename));

			String line;
			int i = 0;
			while ((line = input.readLine()) != null) {
				// System.out.println(line);
				String data[] = line.split(" ");

				String animal = data[0];
				int thisVotes = Integer.parseInt(data[1]);

				animals[i] = animal;
				votes[i] = thisVotes;
				i++;
				totalVotes += thisVotes;
			}

			input.close();
		} catch (FileNotFoundException e) {
			System.out.println(filename
					+ ", containing the survey results, not found");
			e.printStackTrace();
		} catch (IOException e) {
			System.out
					.println("Something went wrong while importing survey results from"
							+ filename);
			e.printStackTrace();
		}

	}

	/**
	 * Store the current voting results into the file. Note the format of the
	 * input file.
	 * 
	 * @throws IOException
	 */
	public void storeResults() throws IOException {
		FileWriter out = new FileWriter(filename);
		// loop through the animals
		for (int i = 0; i < animals.length; i++) {
			// write out the animal, space, votes on separate lines
			out.write(animals[i]);
			out.write(" ");
			// Doesn't seem to work correctly if we try to write the integer --
			// not written as text? Maybe written as binary data because from
			// OutputStreamWriter class
			out.write(String.valueOf(votes[i]));
			out.write("\n");
		}
		out.close();

	}

	/**
	 * 
	 * @return the name of the file containing the survey results
	 */
	public String getFilename() {
		return filename;
	}

	/**
	 * 
	 * @return the array of Strings of animal names in the survey
	 */
	public String[] getAnimals() {
		return animals;
	}

	/**
	 * 
	 * @return the array of integers, representing the number of votes for each
	 *         animal.
	 */
	public int[] getVotes() {
		return votes;
	}

	/**
	 * 
	 * @return the number of votes that have been cast.
	 */
	public int getTotalVotes() {
		return totalVotes;
	}

	/**
	 * Casts a vote for the animal
	 * 
	 * @param animal
	 *            -- must be a valid animal
	 */
	public void castVote(String animal) {
		for (int i = 0; i < animals.length; i++) {
			if (animals[i].equals(animal)) {
				votes[i]++;
				totalVotes++;
				return;
			}
		}
	}

	/**
	 * 
	 * @param animal
	 * @return true iff the animal is a valid animal
	 */
	public boolean validAnimal(String animal) {
		for (int i = 0; i < animals.length; i++) {
			if (animals[i].equals(animal)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Display the results from the survey in a nicely formatted way.
	 */
	public void displayResults() {
		System.out.println("Animal\tVotes\tPercentage");
		for (int i = 0; i < animals.length; i++) {
			double pct = (double) votes[i] / totalVotes * 100;
			System.out.printf("%-6s%7d%12.2f%%\n", animals[i], votes[i], pct);
		}
	}

	/**
	 * @param args
	 *            not used in this program.
	 */
	public static void main(String[] args) {
		final String mySurveyFile = "petSurvey.dat";
		PetSurvey survey = new PetSurvey(mySurveyFile);

		System.out.println("Current Results: ");
		survey.displayResults();

		// Allow User to Vote
		Scanner scanner = new Scanner(System.in);
		System.out
				.print("What animal do you want to vote for as your favorite? (dog, cat, bird, snake, fish, other): ");

		String animalVoted = scanner.nextLine();

		if (!survey.validAnimal(animalVoted)) {
			System.out.println("I'm sorry.  " + animalVoted
					+ " is not a valid selection.");
			System.out.println("Check your spelling or select other.");
		} else {
			survey.castVote(animalVoted);
		}

		// Display updated results
		System.out.println("Updated Results: ");
		survey.displayResults();

		try {
			survey.storeResults();
		} catch (IOException e) {
			System.err.println("Error storing results: ");
			e.printStackTrace();
		}
	}

}

Generated by GNU enscript 1.6.4.