CSCI 151 Lab 6: RPN Calculator
Overview
In this project, you will write a calculator that uses a stack and test it with JUnit.Setup
- Download the skeleton for this project.
- Unpack the code into a new Eclipse Java project.
Description
We saw two implementations of the Stack interface. For this project, you will gain familiarity with the use of stack operations to implement a larger class. In particular, we will investigate how to create a mathematical calculator with a slightly different notation for operations.
An expression such as 2 + 3 * 5
is inherently ambiguous.
To resolve it properly, we need to fix an order of operations,
typically multiplication and division from left to right, then
addition and subtraction. Alternatively, we can use parentheses to
disambiguate. For example, (2 + 3) * 5
means to perform
the addition first, whereas 2 + (3 * 5)
means to perform
the multiplication first.
Alternately, we can use postfix or
Reverse
Polish Notation to embed the precedence in the expression. By placing the operator
at the end instead of in the middle of the two operands, we know exactly
what operation to perform when. For example, the two example
expressions above can be written as
2 3 5 * +
(multiplication first) and
2 3 + 5 *
(addition first).
This model of mathematical operators can be implemented with a stack. When the calculator sees an integer, it should be added to the stack. When it sees an operator (*, +, /, -, %), it should pop the two most recent elements from the stack, perform the operation, and then push the result back on the stack.
When the order of the operation matters, such as a - b
, then your
code should use the first element popped as b
and the
second element popped as a
.
RPNCalc
In therpn.model
package, you will find the following
classes:
RPNCalc.java
This is the main file you will have to complete. You
will need to make a constructor, and complete the other indicated
methods.
- Step 1: Implement the four standard arithmetic
operations together with mod (
%
). This should get your calculator to pass one basic test. - Step 2: Now implement the
methods
getLastValue
,getNextToLastValue
,numValuesLeft
, andtoString
. This should get your calculator to pass several of the remaining tests. - Step 3: Now implement three additional operations:
dup
: When your calculator encounters thedup
instruction, it should duplicate the top value on the stack.swap
: When your calculator encounters theswap
instruction, it should swap the top two values on the stack.pop
: When your calculator encounters thepop
instruction, it should pop the top value from the stack and discard it.
RPNCalcTest.java
These are the unit tests for your calculator. Your grade depends on passing these tests.
Op.java
This is an Enum
. It is used in testing with JUnit, and you can safely ignore it.
What to Hand In
Submit yourRPNCalc.java
file along with
any additional files you created.
© Mark Goadrich, Hendrix College