Contents

  1. ./FindDuplicates.java
  2. ./TestShortcuts.java
  3. ./PetSurvey3.java
  4. ./PlanetTest.java
  5. ./Fruit.java

./FindDuplicates.java 1/5

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

import java.util.HashSet;
import java.util.Set;

/**
 * From the array of command-line arguments, identify the duplicates
 * 
 * @author CS209
 * 
 */
public class FindDuplicates {

	/**
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		Set<String> argSet = new HashSet<String>();
		for(int i=0; i < args.length; i++ ) {
			// try to add argument to set
			if( ! argSet.add(args[i]) ) {
				System.out.println("Duplicate: " + args[i]);
			}
		}
		System.out.println(argSet.size() + " unique words: " + argSet);
	}

}

./TestShortcuts.java 2/5

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

/**
 * Demonstrate use of shortcuts
 * 
 * Pre-operator (i.e., ++i or --i): operation is performed and value is produced
 * Post-operator (i.e., i++ or i--), value is produced, then operation is performed
 * 
 * @author sprenkle
 *
 */
public class TestShortcuts {

	public static void main(String[] args) {
		int i = 1;
		System.out.println("i : " + i); // Output: 1
		System.out.println("++i : " + ++i); // Pre-increment: 2
		System.out.println("i++ : " + i++); // Post-increment: 2
		System.out.println("i : " + i); // 3
		System.out.println("--i : " + --i); // Pre-decrement: 2
		System.out.println("i-- : " + i--); // Post-decrement: 2
		System.out.println("i : " + i); // 1
	}
}

./PetSurvey3.java 3/5

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

import java.io.*;
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 collection.
 * 
 * @author CS209
 * 
 */
public class PetSurvey3 {

	private String filename;
	private int totalVotes = 0;

	Map<String, Integer> petToVotes;
	
	public PetSurvey3(String fn) {
		this.filename = fn;
		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;
			int i = 0;
			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);
				
				i++;
				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() {
		Set<String> animals = petToVotes.keySet();
		String[] animalsArray = (String[]) animals.toArray();
		return animalsArray;
	}

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

	/**
	 * Casts a vote for the animal
	 * 
	 * @param animal
	 */
	public void castVote(String animal) {
		Integer numVotes = petToVotes.get(animal);
		if( numVotes == null ) {
			petToVotes.put(animal, 1);
		} else {
			petToVotes.put(animal, numVotes+1);
		}
		totalVotes++;
	}

	/**
	 * Display the results from the survey in a nicely formatted way.
	 */
	public void displayResults() {
		System.out.printf("%-10s%7s%13s\n", "Animal", "Votes", "Percentage");
		System.out.println("------------------------------");
		
		Set<String> keys = petToVotes.keySet();
		
		for( String animal : keys ) {
			int votes = petToVotes.get(animal);
			double pct = (double) votes/totalVotes * 100;
			System.out.printf("%-10s%7d%12.2f%%\n", animal, votes, pct);
		}
		System.out.println("Total votes cast: " + 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();

		survey.castVote(animalVoted);

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

		survey.storeResults();
	}

}

./PlanetTest.java 4/5

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

/**
 * Example demonstrates a more sophisticated enumerated type.
 *
 */
public class PlanetTest {

	public enum Planet {
		MERCURY(3.302e+23, 2.439e6),
		VENUS(4.869e+24, 6.0518e6),
		EARTH(5.976e+24, 6.37814e6),
		MARS(6.421e+23, 3.3972e6),
		JUPITER(1.9e+27, 7.1492e7),
		SATURN(5.688e+26, 6.0268e7),
		URANUS(8.686e+25, 2.5559e7),
		NEPTUNE(1.024e+26, 2.4746e7);

		private final double mass;
		private final double radius;
		private final double surfaceGravity;

		private static final double G = 6.67300E-11;

		// Note: Package-private; Can't be more visible than package-private
		Planet(double mass, double radius) {
			this.mass = mass;
			this.radius = radius;
			surfaceGravity = G * mass / (radius * radius);
		}

		public double mass() {
			return mass;
		}

		public double radius() {
			return radius;
		}

		public double surfaceGravity() {
			return surfaceGravity;
		}

		public double surfaceWeight(double mass) {
			return mass * surfaceGravity; // F = ma
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		double earthWeight = 150;
        double mass = earthWeight/Planet.EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %10.4f%n",
                             p, p.surfaceWeight(mass));

	}

}

./Fruit.java 5/5

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

/**
 * @author sprenkle
 *
 */
public class Fruit {
	
	public enum Apple {FUJI, PIPPIN, GRANNY_SMITH};
	public enum Orange {NAVEL, TEMPLE, BLOOD};

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

}

Generated by GNU enscript 1.6.4.