Chapter 17: Problem 13
Write class PostfixEvaluator, which evaluates a postfix expression such as $$62+5=84 /-$$ The program should read a postfix expression consisting of digits and operators into a String- Buffer. Using modified versions of the stack methods implemented earlier in this chapter, the pro- gram should scan the expression and evaluate it (assume it is valid). The algorithm is as follows: a) Append a right parenthesis ')' to the end of the postfix expression. When the right- parenthesis character is encountered, no further processing is necessary. b) 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: Push its integer value on the stack (the integer value of a digit character is its value in the computer’s character set minus the value of '0' in Unicode). Otherwise, if the current character is an operator: Pop the two top elements of the stack into variables x and y. Calculate y operator x. Push the result of the calculation onto the stack. c) 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 b) above (based on the sample expression at the beginning of this exercise), if the operator is '/', the top of the stack is 2 and the next element in the stack is 8, then pop 2 into x, pop 8 into y, evaluate 8/2 and push the result, 4, 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: a) Method evaluatePostfixExpression, which evaluates the postfix expression. b) Method calculate, which evaluates the expression op1 operator op2. c) Method push, which pushes a value onto the stack. d) Method pop, which pops a value off the stack. e) Method isEmpty, which determines whether the stack is empty. f) Method printStack, which prints the stack.
Short Answer
Step by step solution
Key Concepts
These are the key concepts you need to understand to accurately answer the question.