Contents

  1. ./PetSurvey3.java

./PetSurvey3.java

package examples;

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 * 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.
 * 
 * Modified to use a Map.
 * 
 * @author CS209
 * 
 */
public class PetSurvey3 {

	private String filename;
	private int totalVotes = 0;

	Map<String, Integer> petToVotes;

	/**
	 * Creates a new Pet Survey, with data extracted from the given file name
	 * 
	 * @param filename
	 *            name of the file containing the data
	 */
	public PetSurvey3(String filename) {
		this.filename = filename;
		petToVotes = new HashMap<String, Integer>();
		importResults();
	}

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

			String line;
			while ((line = input.readLine()) != null) {
				// line format: <animal> <numVotes>
				String data[] = line.split(" ");

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

				petToVotes.put(animal, numVotes);

				totalVotes += numVotes;
			}

			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
	 */
	public void storeResults() {
		try {
			PrintWriter writer = new PrintWriter(filename);

			Set<String> keys = petToVotes.keySet();

			for (String animal : keys) {
				writer.println(animal + " " + petToVotes.get(animal));
			}

			writer.close();

		} catch (IOException e) {
			System.out.println("Error storing survey results to file "
					+ filename);
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * @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() {
		// note that we don't want to give direct access to the animal names
		// because others could try to change them.
		Set<String> animals = petToVotes.keySet();
		String[] animalNames = new String[petToVotes.keySet().size()];
		animals.toArray(animalNames);
		return animalNames;
	}

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

	/**
	 * Returns true iff the given pet is a valid vote
	 * 
	 * @param pet
	 * @return true iff the given pet is a valid vote
	 */
	public boolean validVote(String pet) {
		return petToVotes.containsKey(pet);
	}

	/**
	 * Casts a vote for the animal
	 * 
	 * @param animal
	 */
	public void castVote(String animal) {
		// update vote for the animal

		petToVotes.put(animal, petToVotes.get(animal) + 1);

		totalVotes++;
	}

	/**
	 * Display the results from the survey in a nicely formatted way.
	 */
	public void displayResults() {
		System.out.printf("%-11s%7s%13s\n", "Animal", "Votes", "Percentage");
		System.out.println("-------------------------------");

		String[] sortedPetNames = getAnimals();
		Arrays.sort(sortedPetNames);

		for (String animal : sortedPetNames) {
			int votes = petToVotes.get(animal);
			double pct = (double) votes / totalVotes * 100;
			System.out.printf("%-11s%7d%12.2f%%\n", animal, votes, pct);
		}
		System.out.println("-------------------------------");
		System.out.printf("%-12s%6d\n", "Total Votes:", totalVotes);
	}

	/**
	 * @param args
	 *            not used in this program.
	 */
	public static void main(String[] args) {
		final String mySurveyFile = "petSurvey.dat";
		PetSurvey3 survey = new PetSurvey3(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();
		scanner.close();

		if (!survey.validVote(animalVoted)) {

			System.out.println(animalVoted
					+ " is not a valid pet to vote for.  Please try again");
			System.exit(0);
		}

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

		survey.storeResults();
	}

}

Generated by GNU enscript 1.6.4.