Write class PostfixEvaluator that evaluates a postfix expression such as 6 2 + 5 * 8 4

Question:

Write class PostfixEvaluator that 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 StringBuffer. The program should read the expression and evaluate it (assume it’s valid). The algorithm to evaluate a postfix expression is showing in Fig. 21.20.

Fig. 21.20

123 Append a right parenthesis ) to the end of the postfix expression. When the right-parenthesis character

In lines 4–12 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 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 other operators.] The arithmetic operations allowed in an expression are: + (addition), - (subtraction), * (multiplication), / (division), ^ (exponentiation) and % (remainder).

The stack should be maintained using the modified stack class. 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.

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  answer-question

Java How To Program Late Objects Version

ISBN: 9780136123712

8th Edition

Authors: Paul Deitel, Deitel & Associates

Question Posted: