Assignment 6: RPN Calculator

Your task: write a calculator program that is able to process a term in Reverse Polish Notation (postfix notation).

RPN: in contrast to the "classic" notation of mathematical terms (infix notation), postfix notation puts the operator (e.g. +,-,*,/) behind the two operands (numbers). The infix-term "3+4" becomes "3 4 +", the term

"7*(8+9)*(4-6)" becomes "7 8 9 + * 4 6 - *". The way to process RPN terms is very simple:

·         go through your term from left to right

·         whenever you find an operator, apply it to the 2 operands left from it.

·         replace the 2 operands and the operator in your term by the result of the operation.

·         continue going right until the end.

This algorithm requires a data structure, that offers a convenient replacement. Guess which one that is: yes, a stack. Replacement of 2 operands and the operator with the result translates to: pop the operands from a stack, apply the operation, push the result. It's that simple. So here is the algorithm:

In the following, I will call operands and operators "tokens". I will assume a string that contains an RPN term. Operators/operands (tokens) are separated by space, "7 8 9 + * 4 6 - *" is an example term.

Algorithm:

·         while the term contains more tokens

·         get next token

·         if token is an operand, push it

·         if token is an operator, pop operand1, pop operand2

·         process:  operand2 <operator> operand1 (the order matters for operations like "-", "/", "^" !)

·         push the result

·         on exit: pop end-result from stack.

Task in detail:

·         create a calculator. Input for the basic, non-bonus version is a string read from the keyboard.

·         the calculator has to understand the operations: +(plus),  -(minus), *(times), /(division), %(modulus)

·         the calculator has to deal with wrong user input. If the term is not a valid RPN term, it must output "Invalid Input", and return to the user input.

Hints:

·         JAVA offers a class "String Tokenizer". This class, when applied to a string with separated words/tokens, sequentially returns the single tokens. For example, if the String is "29 4 +", the tokenizer will return "29", "4", "+", "hello" (The "hello" is no operator, so this would not be an RPN term, but is just an example). That's exactly what we need. I will NOT explain how to use the String Tokenizer, you are on your own with its description. You will understand it, since in class we talked about list iterators, which are very similar.

Bonus:

·         3 Bonus points are given if you extend the assignment and create a graphical user interface for the calculator.

·         1 Bonus point is given if you extend the calculator to the operations "sin", "cos". These work on a single operand only, hence the algorithm changes a little (pop only ONE operand).

Deadlines:

·         10/16 for 10 points, 10/23 for 6 points.

Enjoy!