Q12Write a method postfixEvaluate that accepts a postfix exp
Q.12Write a method postfixEvaluate that accepts a postfix expression string, evaluates it, and returns the result. ÐAll operands are integers; legal operators are + and * postFixEvaluate(\"1 2 3 * + 4 +\") returns 11 use java
Solution
to evaluate the expressions using staks is the good option.
import java.util.*;
public class Postfix {
public static void main(String[] args) {
System.out.println(\"Given expression is:1 2 3 * + 4 +\");
System.out.println(postfixEvaluate(\"1 2 3 * + 4 +\"));
}
public static int postfixEvaluate(String exp) {
Scanner operands = new Scanner(exp);
Stack<Integer> s = new Stack<Integer> ();
while (operands.hasNext()) {
if (operands.hasNextInt()) {
s.push(operands.nextInt());
} else {
int num1 = s.pop();
int num2 = s.pop();
String op = operands.next();
if (op.equals(\"+\")) {
s.push(num1 + num2);
} else if (op.equals(\"*\")) {
s.push(num1 * num2);
} else {
}
}
}
return s.pop();// return result of the expression
}
}
