// CSE 143, Winter 2010, Marty Stepp // Homework 4: Affection // // Instructor-provided testing program. import java.io.*; import java.util.*; /** Class AffectionMain is the main client program for assassin game management. It reads names from a file names.txt, shuffles them, and uses them to start the game. The user is asked for the name of the next sweetheart until the game is over. */ public class AffectionMain { /** input file name from which to read data */ public static final String INPUT_FILENAME = "names.txt"; /** true for different results every run; false for predictable results */ public static final boolean RANDOM = true; /** If not random, use this value to guide the sequence of numbers that will be generated by the Random object. */ public static final int SEED = 42; public static void main(String[] args) throws FileNotFoundException { // read names into a Set to eliminate duplicates File inputFile = new File(INPUT_FILENAME); if (!inputFile.canRead()) { System.out.println("Required input file not found; exiting.\n" + inputFile.getAbsolutePath()); System.exit(1); } Scanner input = new Scanner(inputFile); Set names = new TreeSet(String.CASE_INSENSITIVE_ORDER); while (input.hasNextLine()) { String name = input.nextLine().trim().intern(); if (name.length() > 0) { names.add(name); } } // transfer to an ArrayList, shuffle and build an AffectionManager List nameList = new ArrayList(names); Random rand = (RANDOM) ? new Random() : new Random(SEED); Collections.shuffle(nameList, rand); AffectionManager manager = new AffectionManager(nameList); // prompt the user for sweethearts until the game is over Scanner console = new Scanner(System.in); while (!manager.isGameOver()) { oneKiss(console, manager); } // report who won System.out.println("Game was won by " + manager.winner()); System.out.println("Final schoolyard is as follows:"); manager.printSchoolyard(); } /** Handles the details of recording one sweetheart. Shows the current kiss ring and schoolyard to the user, prompts for a name and records the kiss if the name is legal. */ public static void oneKiss(Scanner console, AffectionManager manager) { // print both linked lists System.out.println("Current kiss ring:"); manager.printKissRing(); System.out.println("Current schoolyard:"); manager.printSchoolyard(); // prompt for next sweetheart to kiss System.out.println(); System.out.print("next sweetheart? "); String name = console.nextLine().trim(); // kiss the sweetheart, if possible if (manager.schoolyardContains(name)) { System.out.println(name + " is already kissed."); } else if (!manager.kissRingContains(name)) { System.out.println("Unknown person."); } else { manager.kiss(name); } System.out.println(); } }