Lab 4: Stacks and The Postfix Calculator
CS 241: Data Structures, Fall 2007


Due Date: class on Monday Oct 1

Goals for this assignment are to learn about:

Reading

Chapter 4

Stack Based Calculator

Postfix Calculator: Project 4.20 on pages 116-117 describes postfix notation. Your job is to write a calculator program that calculates the numeric value of a postfix expression containing numbers and the operators +, -, *, /

(in the picture, ignore the "Calculate Infix" button for the moment).

Below are some suggestions:

Stack Based Queue

Implement the DoubleStackQueue as described in problem 4.19 on p 116. Use the Java Stack (java.util.Stack) for your stack. The DoubleStackQueue should implement the Queue interface given on p. 109. If you have trouble with generics, please ask! Your program should have three different files:

Extra Credit (2 pts) - Infix Calculator

Don't try this unless you have completed all of the above tasks.

Add another JButton to your postfix calculator which calculates infix expressions containing numbers, parentheses, and the 4 operations: +,-,*,/. The way to do this is to convert the infix expression to postfix and then use your postfix calculator to compute the result. Converting from infix to postfix also uses a stack but is trickier than you might think. Roughly, the procedure is as follows (I took this off the web):

Algorithm to convert from infix to postfix

  1. Examine the next element in the input.
  2. If it is an operand, output it.
  3. If it is opening parenthesis, push it on stack.
  4. If it is an operator, then
    1. If stack is empty, push operator on stack.
    2. If the top of the stack is opening parenthesis, push operator on stack.
    3. If it has higher priority than the top of stack, push operator on stack.
    4. Else pop the operator from the stack and output it, repeat step 4.
  5. If it is a closing parenthesis, pop operators from the stack and output them until an opening parenthesis is encountered. pop and discard the opening parenthesis.
  6. If there is more input go to step 1
  7. If there is no more input, unstack the remaining operators to output.

Evaluation

By no later than class on Oct 1, you should do the following:

  1. Make sure your project includes a working jar file.
  2. Zip together both the Calculator and the DoubleStackQueue projects.
  3. Email the code as an attachment to gorr@willamette.edu. Place CS241 Lab 4 in the subject line.

Demo your programs no later than Thurs, Oct 4.


[top]  [Schedule]  [Home]