// CSE 143, Winter 2011, 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 Exams { public static void main(String[] args) throws FileNotFoundException { // read the lines from the file (in reverse ABC order) into a stack Scanner input = new Scanner(new File("exams.txt")); Stack s = new Stack(); while (input.hasNextLine()) { String line = input.nextLine(); // "Todd Kim 52" s.push(line); } // filter out the students who got 100 on the exam Queue q = new LinkedList(); while (!s.isEmpty()) { String line = s.pop(); if (!line.endsWith("100")) { q.add(line); } } // print all of the students' information in ABC order int size = q.size(); for (int i = 0; i < size; i++) { String line = q.remove(); System.out.println(line); q.add(line); } System.out.println(q); Stack backup = new Stack(); while (!s.isEmpty()) { String line = s.pop(); System.out.println(line); backup.push(line); } // System.out.println("Top students:"); // while (!backup.isEmpty()) { // String line = backup.pop(); // if (line.endsWith("100")) { // System.out.println(line); // } // } // Why it's usually bad to do a for loop from i=0 to size(): // i size // 0 21 // 1 20 // 2 19 // 3 18 // 4 17 // ... // 11 10 } }