// CSE 143, Autumn 2015 // This program demonstrates the use of stacks and queues. // It reads in a file of students' exam scores in reverse order, such as: // // Zahn William 92 // Yu Vivian 95 // Wolf Adam 87 // // And first strips the ones who got 100 on the exam using a queue, // then prints the rest in reverse order using a stack. // WARNING: this is an example of how to use stacks and queues, // not an example of good code. import java.util.*; import java.io.*; public class Exams { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("ta.txt")); Queue tas = new LinkedList(); // read the lines from the file (in reverse ABC order) into a queue while(input.hasNextLine()) { tas.add(input.nextLine()); } // filter out the students who got 100 on the exam // WARNING: we wrote the code this way as a demonstartion of how to loop // through a queue. In your homework and other coding you should // combine loops when possible and not write them like this. int size = tas.size(); for(int i = 0; i < size; i++) { String ta = tas.remove(); if(!ta.endsWith("100")) { tas.add(ta); } } // move all of the tas to a stack to reverse them Stack reverse = new Stack(); while(!tas.isEmpty()) { reverse.push(tas.remove()); } // move the tas back to the queue and print them out in // alphabetical order while(!reverse.isEmpty()) { String ta = reverse.pop(); System.out.println(ta); tas.add(ta); } // restore tas to their original order in the LinkedList while(!tas.isEmpty()) { reverse.push(tas.remove()); } while(!reverse.isEmpty()) { tas.add(reverse.pop()); } } }