CS 1723 -- Answer to Exercise in Week 3
A Simple Stack of Chars


Here is an answer to the Exercise in Week 3.

// CharStackMain: Use Java's library Stack class (legacy)
//   Print a string in reverse order by pushing first on a stack
import java.util.*; // for the Stack class and the exception class
public class CharStackMain { 

   public static void main(String[] args) {
      // string to use for data
      String str = new String("The quick brown fox jumps over the lazy dog");
      // create two stacks of Objects
      Stack s = new Stack();
      Stack t = new Stack();
      // push chars from the string onto the stacks.  Need wrappers.
      //  Can assign Character to Object, but not char to Object
      for (int i = 0; i < str.length(); i++) {
         Object obj = new Character(str.charAt(i)); // wrapper for ith char
         s.push(obj); t.push(obj);
      }

      // pop and print the first stack, using empty()
      //   method to terminate loop
      while (!s.empty())
         System.out.print(s.pop());
      System.out.println("\nEnd of the first stack");

      // pop and print 2nd stack, using EmptyStackException
      //   to terminate loop (not the preferred method)
      while (true) {
         try {
            System.out.print(t.pop());
         } catch (EmptyStackException ese) {
            break;
         }
      }
      System.out.println("\nTh-th-th-th-that's-all-folks");
   }
}
Sample run.
ten42% java CharStackMain
god yzal eht revo spmuj xof nworb kciuq ehT
End of the first stack
god yzal eht revo spmuj xof nworb kciuq ehT
Th-th-th-th-that's-all-folks
ten42% 

Revision date: 2001-09-25. (Please use ISO 8601, the International Standard.)