// CSE 143, Winter 2012 // This program evaluates "postfix" expressions (also called "Reverse Polish // Notation"), which are mathematical expressions but with the operators placed // after operands instead of between. // For example: 1 + 2 * 3 + 4 is written as 1 2 3 * + 4 + import java.util.*; public class Postfix { public static void main(String[] args) { System.out.println(postfixEvaluate("1 2 3 +")); // 3 System.out.println(postfixEvaluate("1 2 3 * + 4 +")); // 11 System.out.println(postfixEvaluate("5 2 4 * + 7 -")); // 6 System.out.println(postfixEvaluate("2 3 + 4 5 * +")); // 25 System.out.println(postfixEvaluate("8 5 * 7 4 2 + * +")); // 82 System.out.println(postfixEvaluate("6 8 2 / 1 - *")); // 18 } // Evaluates the given postfix expression string and returns the result. // Precondition: expression consists only of integers, +-*/, and spaces in // proper postfix format such as "2 3 - 4 *" public static int postfixEvaluate(String expression) { Stack stack = new Stack(); Scanner tokens = new Scanner(expression); while (tokens.hasNext()) { if (tokens.hasNextInt()) { // operand (number) int num = tokens.nextInt(); stack.push(num); } else { // operator (string) String operator = tokens.next(); // "*" "-" int num2 = stack.pop(); int num1 = stack.pop(); int result; if (operator.equals("+")) { result = num1 + num2; } else if (operator.equals("-")) { result = num1 - num2; } else if (operator.equals("*")) { result = num1 * num2; } else { // if (operator.equals("/")) { result = num1 / num2; } stack.push(result); } } // there SHOULD be exactly 1 thing on the stack now return stack.pop(); } }