| CIS 210 Home Page | Last updated 2007/11/13 20:31:40 |
Postfix notation, also called reverse Polish notation, can be used to write arithmetic expressions without parentheses. Instead of writing (3+5)*7, in postfix notation we write
3 5 + 7 *
Postfix expressions can be evaluated using a stack. The steps in evaluating the expression above are: Push 3, push 5; pop top two values, add them, and push the result; push 7; pop top two values, multiply them, and push the result. (Other operations like subtraction work similarly).
You will construct a program that reads a postfix expression from the keyboard and executes it. In addition to positive integers and arithmetic operators, the postfix expression can contain a few other commands:
| argument | action | example input | example output |
|---|---|---|---|
| (positive integer) | push integer on stack | 88 = | 88 |
| = | print top value on stack on a line by itself (without changing the stack) | 88 = 7 3 + = | 88 10 |
| C | clear stack (returns to initial, empty state) | 88 35 C = | No current value! |
| + | addition | 5 4 + 3 + = | 12 |
| - | subtraction | 15 5 - 4 - = | 6 |
| * | multiplication | 3 7 * = | 21 |
| / | integer division | 7 3 / = | 2 |
| % | modulus (like % in Java) | 7 3 % = | 1 |
| Q | Quit the calculator program | Q |
You can start the calculator from TextPad - just make sure that you do not have capture output checked in "Run Java Application" preferences. You can also start from a command prompt by
In either case, the program will wait for you to type input. You type in expressions, for example:> java Calculator
(The program responses are in italics.)3 5 + 7 * = 56 C 15 5 - 4 - = 6 82 + = 7 3 + = 88 10 Q
This calculator does not crash or print an error message when the expression is illegal. It uses a slightly odd stack, which can be popped even when it is empty. Popping the empty stack returns zero. Therefore, if you evaluate this malformed expression:
the result printed will be 9; after the first addition of 2 to 7, the rest add 0 to 9 and leave 9 on the stack.4 2 - 7 + + + + + =
You should check for the possibility of division by zero and make sure that no exception is generated. You can either ignore division by zero or have it result in a value of zero.