numstack.model
class from the 151-stacks project in Lab
3. You will need a working implementation of the Stack interface that has passed
all the JUnit tests of Lab 3.
An expression such as 2 + 3 * 5
is ambiguous by itself, only
looking at syntax. To resolve it
properly we need to use the order of operations: Multiplication, then Division, then Addition,
then Subtraction, or use parenthesis to force our order. (2 + 3) * 5
is different than 2 + (3 * 5)
.
Alternately, we can use
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. Our ambiguity disappears, since the above expression
will need to be written as
2 3 5 * +
or
2 3 + 5 *
depending on the desired result.
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
.
rpn.model
package, you will find the following
classes:
RPNCalc.java
RPNCalcTest.java
Op.java