Project 4: RPN Calculator

The goal of this project is to practice using stacks in an algorithm.

1. Introduction

Polish mathematician Jan Lukasiewicz invented a notation for arithmetic where the operator comes before the operands, for example + 5 3 instead of 5 + 3. The advantage of this is that the order of operation is always unambiguous without the need for parentheses (or even precedence rules). For example, 5 * 3 - 9 is written - * 5 3 9, whereas 5 * (3 - 9) is written * 5 - 3 9. In honor of its inventor (or his nationality, at any rate), this is referred to as Polish notation. (It is also called prefix notation, in contrast to normal arithmetic notation which is thus infix.)

Reverse Polish notation is similar except that the operator is put after the operands (so it is also postfix notation). The advantage is that all the operands are then known before the operator is read, if we read the string from left to right. This notation is particularly interesting for our purposes, because a stack can be used to evaluate expressions in RPN. Your task is to write a calculator that evaluates expressions entered in RPN.

2. Setup

In this project you will use the same GUI as in the earlier calculator example. After making the directory for this project, copy the following files from the course public directory:

cp /homeemp/tvandrun/pub/245/CalculatorFace.java .
cp /homeemp/tvandrun/pub/245/ConcreteCalculatorFace.class .
cp /homeemp/tvandrun/pub/245/ConcreteCalculatorFace\$1.class .

3. Calculator details

One difficulty in using RPN, especially on a simulated hand-held calculator, is how to delimit the operands. The string 937+ could mean 9 + 37 or 93 + 7. In a string, this disambiguation would be done using spaces. For your calculator, you should interpret the "." button as indicating the boundary between numbers. Consequently, your calculator needs to work only on integers; division should be integer division.

Even though this section of the course is about data structures, you should keep thinking about object-oriented design. To push you in this, there will be an extra rule for your calculator code: You may never use an if statement or a switch statement. That is, all decision-making must be done using polymorphism.

4. To turn in

Copy all the files you made or modified to a turn-in directory I've made for you.

cp filename /homeemp/tvandrun/turnin/245/{jessica,sam,chet,jan}

DUE: Monday, Mar 19, 5:00 pm.


Thomas VanDrunen
Last modified: Tue Mar 13 10:55:55 CDT 2007