// CSE 143, Winter 2009, Marty Stepp // // This program demonstrates the use of stacks and queues. // It reads in a file of students' exam scores in reverse order, such as: // // Yeilding Janet 87 // White Steven 84 // Todd Kim 52 // // And first strips the ones who got 100 on the exam using a queue, // then prints the rest in reverse order using a stack. import java.io.*; import java.util.*; public class GradeExams { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("exams.txt")); Queue students = readStudents(input); System.out.println(students); remove100s(students); System.out.println(students); printReversed(students); System.out.println(students); } // Reads the given file into a queue and returns it. public static Queue readStudents(Scanner input) { Queue students = new LinkedList(); while (input.hasNextLine()) { String line = input.nextLine(); students.add(line); } return students; } // I have the students in a queue; now remove students with score of 100 public static void remove100s(Queue students) { int size = students.size(); for (int i = 0; i < size; i++) { String student = students.remove(); // "Todd Kim 52" if (!student.endsWith("100")) { students.add(student); } } } // Prints the contents of the given queue in reverse order. // Postcondition: The queue is unmodified from its original state when the method returns. public static void printReversed(Queue students) { Queue backup = new LinkedList(); Stack s = new Stack(); // load all students into a stack (for printing) and backup queue (for restoring) while (!students.isEmpty()) { String line = students.remove(); backup.add(line); s.push(line); } // print the elements of the queue in reverse order (using the stack) while (!s.isEmpty()) { System.out.println(s.pop()); } // restore the queue to its original state while (!backup.isEmpty()) { students.add(backup.remove()); } } }