SIMS 255 Lab 7: Using Stacks

    Wednesday, October 9, 2002

    Programming with Java's Stack class


    To get some practice using stacks, implement a reverse-polish notation calculator (like we saw in class) using java.

    Using command-line input

    One way to do this is to have the calculator accept input of the following form:

      3
      2
      +
      5
      *
      =

    After each command you can have the calculator print out what's at the top of the stack without popping it. Or you can have the program print out the entire stack (this is not what calculators usually do, but will help you debug). If the user enters "=", this pops the number off the top of the stack and also prints it out. The code should print out an error if the user tries to do an operation when the stack is empty.

    Java has the stack as a built-in type. You use it by including java.util.* in your code. Here is a link to the API of the stack class in Java, look it over and try to understand what kind of information is being given to you here.

    http://java.sun.com/j2se/1.3/docs/api/java/util/Stack.html

    We are providing you with the Calulator.java file as a starting point for the problem.

    Using File-Based Input and the StringTokenizer class

    To practice the concept of String Tokenization, create a text file with a line of input like:

    3 2 + 5 * =

    Now add code to your Calculator program so it can open this file and read in the line and use the StringTokenizer class to break the line into separate "words" (in this case, single letter words) for the Calculator to use as input.

    Here is the link to the API for Java's StringTokenizer class:
    http://java.sun.com/j2se/1.3/docs/api/java/util/StringTokenizer.html

    An example of processing "words" using StringTokenizer

    Stack myStack = new Stack();
    String line = "Mary had a litte lamb";
    StringTokenizer st = new StringTokenizer(line);

    while (st.hasMoreTokens()) {
         String token = st.nextToken();
         myStack.push(token);
    }

    Be aware though that the items in your Stack are now all of type String. For the Calculator, you will need to cast the numbers back into type int after you pop them. Another way to do this is to add code in the while loop above to convert your String tokens to objects of type Integer (unless it is an operator like '+' or '=').

    Calculator Psuedocode Example

    The Calculator can use the following pseudocode if you like (you can implement the 'subtract' ('-') function too):

    get the input

    if the input is

         an integer,
              push it on the stack

         a +, then
              res = pop();
              res = res + pop();
              push res;
              print res;

         a *, then
              res = pop();
              res = res * pop();
              push res;
              print res;

         an =, then
              res = pop();
              print res;