// CSE 143, Autumn 2013 // 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 + +")); // 6 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); while(input.hasNext()) { if(input.hasNextInt()) { s.push(input.nextInt()); } else { String op = input.next(); int operand2 = s.pop(); int operand1 = s.pop(); if(op.equals("+")) { s.push(operand1 + operand2); } else if(op.equals("-")) { s.push(operand1 - operand2); } else if(op.equals("*")) { s.push(operand1 * operand2); } else if(op.equals("/")) { s.push(operand1 / operand2); } } } return s.pop(); } }