Write class PostfixEvaluator, which evaluates a postfix expression such as
6 2 + 5 * 8 4 / -
The program should read a postfix expression consisting of digits and operators into a StringBuilder. Using modified versions of the stack methods implemented earlier in this unit, the program should scan the expression and evaluate it (assume it is valid). The algorithm is as follows:
)
to the end of the postfix expression. When the right parenthesis character is encountered, no further processing is necessary.When the right-parenthesis character has not been encountered, read the expression from left to right.
If the current character is a digit, do the following:
Otherwise, if the current character is an operator:
x
and y
.y
operator x
.When the right parenthesis is encountered in the expression, pop the top value of the stack. This is the result of the postfix expression.
[Note: In 2. above (based on the sample 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 8, then pop 4 into x, pop 8 into y, evaluate 8 / 4 and push the result, 2, back on the stack. This note also applies to operator ’-’.]
The arithmetic operations allowed 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:
int evaluatePostfixExpression(String postfix)
, which evaluates the postfix expression.int calculate(int op1, char oper, int op2)
, which evaluates the expression op1
operator op2
.As you can see, the only type to be stored on the stack is Integer
. Use the following method to convert the stored Character
s into Integer
s:
public Integer charToInt(Character c)
{
return Character.getNumericValue(c);
}