// CSE 143, Winter 2009, Daniel Otero // This program hires and fires teaching assistants based on their experience. // It is a demonstration of the PriorityQueue class. import java.io.*; import java.util.*; public class FiringSquad { private static final int MINIMUM_EXP = 3; private static final String TAS_FILE = "tas.txt"; private static final String REPLACEMENTS_FILE = "replacements.txt"; public static void main(String[] args) throws IOException { List taList = getTAsFromFile(TAS_FILE); System.out.println(taList); System.out.println(); // Get TAs into sorted order somehow Queue queue = new PriorityQueue(); for (TA ta : taList) { System.out.println("Just added TA: " + ta); queue.add(ta); printQueue(queue); System.out.println(); } // Find all the TAs with < MINIMUM_EXP quarters of experience // (Elements come out of the queue in sorted order, least to greatest, // regardless of the order in which they were inserted.) while (!queue.isEmpty() && queue.peek().getExperience() < MINIMUM_EXP) { TA ta = queue.remove(); System.out.println("Removed TA: " + ta); } // Replace fired TAs with new ones from the replacements file List replacements = getTAsFromFile(REPLACEMENTS_FILE); for (TA replacement : replacements) { queue.add(replacement); } System.out.println(); System.out.println("Final queue:"); printQueue(queue); } // Given a file name, attempts to read the names and experience levels of // TAs from that file. Each TAs data is inserted into a TA object, and the // lot are returned in a list. private static List getTAsFromFile(String filename) throws IOException { Scanner fileScanner = new Scanner(new File(filename)); List tas = new ArrayList(); while (fileScanner.hasNext()) { String taName = fileScanner.next(); int taExp = fileScanner.nextInt(); tas.add(new TA(taName, taExp)); } return tas; } // Prints contents of given priority queue in order they would be removed. // PriorityQueue#toString() doesn't suffice: doesn't show ordering. private static void printQueue(Queue queue) { Queue backup = new LinkedList(); System.out.print("["); if (!queue.isEmpty()) { System.out.print(queue.remove()); while (!queue.isEmpty()) { TA ta = queue.remove(); System.out.print(", " + ta); backup.add(ta); } } System.out.println("]"); while (!backup.isEmpty()) { queue.add(backup.remove()); } } }