Contents

  1. ./InvoiceUsingText.java
  2. ./PetSurvey2.java
  3. ./ConsoleIODemo.java
  4. ./PetSurvey.java

./InvoiceUsingText.java 1/4

[
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 {

		// I know I don't want this variable to change within this method, so
		// made it final
		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 FileInputStream(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();

		// old way
		System.out.println("For a TOTAL of $" + total);
		// 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 2/4

[
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]++;
				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();
		}
	}

}

./ConsoleIODemo.java 3/4

[
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);

		System.out
				.print("Please enter the width of a rectangle (as an integer): ");

		while (!scan.hasNextInt()) {
			scan.nextLine();
			System.out.println("Error: input was not an integer.");
			System.out
					.print("Please enter the width of a rectangle (as an integer): ");

		}

		int width = scan.nextInt();

		System.out
				.print("Please enter the height of a rectangle (as an integer): ");
		while (!scan.hasNextInt()) {
		    scan.nextLine();
		    System.out.println("Error: input was not an integer.");
		    System.out
					.print("Please enter the height of a rectangle (as an integer): ");
		}

		int length = scan.nextInt();

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

}

./PetSurvey.java 4/4

[
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 (we ran into a bit of trouble)
 * 
 * @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(" ");
			// We ran into trouble because we were trying to write an
			// int, so it wrote it as an ASCII character
			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]++;
				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.