You will create a very simple postfix calculator. If you are unfamiliar with postfix, this is a system in which you enter the operands first, then the operators. For example, to compute 4.56 + 7.89, you would enter the operations in the following order
4.56
7.89
Add
Far from being artificial, this is in fact how all computers and calculators work. Your graphing calculator merely transforms what you enter into this form before completing the calculation.
You will enter a series of numbers or operations, then the calculator will compute the result. Specifically, your calculator will allow you to enter floating point numbers, and then perform the operations of addition, multiplication, square-root, cosine and tangent. You will enter the operations desired by entering single letters. The list of operations is
Token to be entered | Operation |
A | Addition |
M | Multiplication |
C | Cosine |
S | Square-root |
T | Tangent |
Q | Quit: no more tokens to be entered: perform calculation |
The operations are entered in a post-fix fashion. That is, the operator is always invoked after its operands are already available.
For example, to compute the formula square root of cos(1.23 + 78.9) you would enter the following into your calculator
1.23 < enter>
78.9 < enter>
A < enter>
C < enter>
S < enter>
Q < enter>
The taxonomy of the operations is shown below: see image.
You will place the operands, all of type double, onto a stack, say operandStack. The operators will work on values in this stack.
The base class Operator has one abstract method called evaluate that works with values it finds on this stack. Specifically, for a literal value, the evaluate function merely pushes the literal value onto the stack. The unary operators pop one value off the stack, perform the needed computation and push the result back onto the stack. The binary operators pop two values off the stack, perform the needed operation and push the single operation back onto the stack.
When your program begins, you will accept input from the user. You should inspect the input and construct instances of the various operators according to what the user enters. You should also warn the user if she enters an illegal input. You will place the instances of the operators you construct into a queue.