// CSE 143, Winter 2010, Marty Stepp // 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 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 s = new Stack(); Scanner input = new Scanner(expression); // "5 2 4 * + 7 -" while (input.hasNext()) { if (input.hasNextInt()) { // an operand; a number like 5 2 4. push it onto the stack s.push(input.nextInt()); } else { // an operator + - * int right = s.pop(); int left = s.pop(); String operator = input.next(); // "+", "*" // left operator right if (operator.equals("+")) { s.push(left + right); } else if (operator.equals("-")) { s.push(left - right); } else if (operator.equals("*")) { s.push(left * right); } else { // operator.equals("/") s.push(left / right); } } } return s.pop(); // last remaining element on stack is the answer } }