Description
A simple command prompt calculator that uses Reverse Polish Notation.
In Reverse Polish Notation the operators follow their operands; for instance, to add three and four, one would write “3 4 +” rather than “3 + 4″. If there are multiple operations, the operator is given immediately after its second operand; so the expression written “3 − 4 + 5″ in conventional infix notation would be written “3 4 − 5 +” in RPN: first subtract 4 from 3, then add 5 to that.
The algorithm for evaluating any postfix expression is fairly straightforward:
- While there are input tokens left
- Read the next token from input
- If the token is a value
- Push it onto the stack
- Otherwise, the token is an operator
- It is known a priori that the operator takes n arguments
- If there are fewer than n values on the stack
- (Error) The user has not input sufficient values in the expression.
- Else, Pop the top n values from the stack.
- Evaluate the operator, with the values as arguments
- Push the returned results, if any, back onto the stack
- If there is only one value in the stack
- That value is the result of the calculation
- If there are more values in the stack
- (Error) The user input too many values
For more information on Reverse Polish Notation read: http://en.wikipedia.org/wiki/Reverse_Polish_Notation.
Technical Knowledge
I applied my knowledge of:
- object oriented programming in Java
- Reverse Polish Notation
- polymorphism.
Skills Applied
I developed these skills while making this artifact:
- using the NetBeans IDE
- test-driven design using Netbeans
- object oriented programming with Java.
Notes
I wrote this for BCIT’s COMP 2526, Intermediate Java, in February 2008.
I employed an iterative, test-driven approach. My first iteration resulted in a program that used classes to deal with different operations. The second iteration reduced code duplication and improved the quality of the code with polymorphism.
The application was written using NetBeans against a series of Unit tests provided by our instructor, D’Arcy Smith.
Demonstration
Download the source code [8 KB ZIP].
Download the JAR file here [13 KB]. Navigate to the download folder with your command prompt and run using:
java -jar RPN_2.jar