Reference no: EM1355567
Write a class PostFixEvaluator that evaluates postfix expression such as 6 2 + 5 * 8 4 / -. The program should read a postfix expression consisting of digits and operators into a StringBuffer. Using modified version of Stack Data Structures(Abstract Data Structures -ADT) and it accompanying methods, your program should scan the expression and evaluate it ( assume it is legal/valid). The algorithm is as follows:
a. Append a # to the end of the postfix expression. When the# character is encountered, no further processing is necessary.
b. When the # character has not been encountered, read the expression from left to right.
i. If the character is a digit, do the following:
1. Push its integer value on the stack ( the integer value of a digit character is its value in the Unicode character set minus the value of '0' in Unicode.
2. Otherwise if the current character is an operator:
a. Pop the two top elements of the stack into variables x and y.
b. Calculate y operator x
c. Push the result of the calculation onto the stack.
3. When the # character is encountered in the expression, pop the top value of stack. This is the result of the postfix expression.
c. Note that in b above( based on the same expression at the beginning of this exercise), if the operator is '/' the top of the stack is 4 and the next element in the stack is 40 then pop 4 into x pop 40 into y, evaluate 40 / 4 and push the result, 10 back on the stack. This note also applies to operator '-'. This arithmetic operations allowed in an expression in an expression are:
+ - addition
- - subtraction
* - multiplication
/ -division
^ -exponentiation
% - remainder
The stack should be maintained with one of the stack classes introduced in this chapter. You may want to provide the following methods.
a) Method evaluatePostFixExpression, which evaluates the postfix expression
b) Method calculate, which evaluates the expression op1 operator op2.