Scientific Programming II

Programming in Java

Stacks Quiz


Problem 1 (15 Points)

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:

  1. Append a right parenthesis ) to the end of the postfix expression. When the right parenthesis character is encountered, no further processing is necessary.
  2. When the right-parenthesis character has not been encountered, read the expression from left to right.

  3. 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:

  1. int evaluatePostfixExpression(String postfix), which evaluates the postfix expression.
  2. int calculate(int op1, char oper, int op2), which evaluates the expression op1 operator op2.
Helpful Hints

As you can see, the only type to be stored on the stack is Integer. Use the following method to convert the stored Characters into Integers:

public Integer charToInt(Character c)
{
    return Character.getNumericValue(c);
}