# Exercise 2B -- to be done

## A Simple Postfix Calculator

In this part of the exercise you will build a simple reverse polish (or postfix) calculator. That is, one that accepts arithmetic expressions like 23 + 4 in the form 23 4 +.

You are given the following piece of pseudocode that describes an algorithm for evaluating a postfix arithmetic expression:

```   WHILE more symbols in expression DO
symbol <- next symbol
IF symbol is an operand THEN
push symbol onto stack
ELSE (symbol is an operator)
op1 <- pop stack
op2 <- pop stack
value <- result of applying symbol to op1 and op2
push value onto stack
ENDIF
ENDWHILE
result <- pop stack
```

Your program should should ask the user for a valid postfix expression and then evaluate it and print out the result.

### Hints

1. Take a look at the SimpleCalc.java program for some ideas on how to structure your program
2. You should use an instance of the java.util.Stack class as your stack. Find out how to use it from the Java API. Remember to import it!
3. Because the stack only stores Java objects and not primitive types, you will have to wrap your ints with instances of the java.lang.Integer class. e.g.
• Integer operand = Integer.getInteger( input );
• int total = operand1.intValue() + operand2.intValue();
• Integer result = new Integer( total );
4. You should use the java.util.StringTokenizer class as a method of parsing the user's input. Find out about it from the Java API.
5. Think carefully about what sort of error conditions your program might encounter and try to write your program so that it catches them
6. Other arithemtic expressions that you should test your program with are (infix/postfix):
• 12 / 3
12 3 /
• 4 * 3 - 5
4 3 * 5 -
• (123 * 2) + 12 * (44 - 1)
123 2 * 12 44 1 - * +

## Extras

If your calculator doesn't already, it should allow users to enter more than one expression before quitting, perhaps by asking "Do you wish to enter another?" before exiting.

© 2001 Mark Ryan and Alan Sexton