// CSE 143, Winter 2009, 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(evaluate("1 2 +")); // 3 System.out.println(evaluate("1 2 3 * + 4 +")); // 11 System.out.println(evaluate("2 3 + 4 5 * +")); // 25 System.out.println(evaluate("8 5 * 7 4 2 + * +")); // 82 } // Evaluates the given prefix expression string and returns its result. // Precondition: expression string represents a legal postfix expression // containing only integers and + and * public static int evaluate(String expression) { Stack s = new Stack(); Scanner input = new Scanner(expression); while (input.hasNext()) { if (input.hasNextInt()) { // an operand (a number); push it onto the stack s.push(input.nextInt()); } else { // an operator (+ or *); apply it to the top two operands on the stack String operator = input.next(); // "+" , "*" int operand2 = s.pop(); int operand1 = s.pop(); if (operator.equals("+")) { s.push(operand1 + operand2); } else { s.push(operand1 * operand2); } } } return s.pop(); } }