import java.util.Stack; import java.util.StringTokenizer; /** * Programming Project 3-3 * * @author:(your name here) * * Evaluates a postfix expression that operates on integer operands * using the arithmetic operators +, -, *, /, and %. Inputs is * assumed to be in valid postfix form. */ public class PostfixEvaluator { //Stack stack; /** * Helper method that parses the string and returns the int value. * if the string is invalid, return -1. */ private static int getIntValue(String s) { int result = -1; try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // does nothing } return result; }// end getIntValue /** * Evaluates the postfix expression and returns the result */ public static double evaluate(String expression) { char character; String word = ""; Stack stack = new Stack(); double first = 0.0; double second = 0.0; StringTokenizer tokenizer = new StringTokenizer(expression); while(tokenizer.hasMoreTokens()) { word = tokenizer.nextToken(); if(word.equals("+") || word.equals( "-") || word.equals("*") || word.equals("/")) { character = word.charAt(0); first = Double.parseDouble(stack.pop().toString()); second = Double.parseDouble(stack.pop().toString()); switch(character) { case '+': stack.push(new Double(first + second)); break; case '-': stack.push(new Double(second - first)); break; case '*': stack.push(new Double(first * second)); break; case '/': stack.push(new Double(second / first)); break; } } else { stack.push(new String(word)); } } // finish this method return Double.parseDouble(stack.pop().toString()); }// end evaluate /** * main method, used for testing the static * method PostfixEvaluator.evaluate(). Can be * removed when testing complete. */ public static void main (String args[]) { System.out.println("Postfix Evaluator"); System.out.println("------- ---------"); String expression = "5 2 + 8 5 - *"; System.out.println(expression); System.out.println("Result : " + PostfixEvaluator.evaluate(expression)); expression = "2 4 - 5 2 * +"; System.out.println("\n" + expression); System.out.println("Result : " + PostfixEvaluator.evaluate(expression)); expression = "9 3 / 6 / 4 * 10 -"; System.out.println("\n" + expression); System.out.println("Result : " + PostfixEvaluator.evaluate(expression)); expression = "9 3 / 6 / 4 * 10 - 4 /"; System.out.println("\n" + expression); System.out.println("Result : " + PostfixEvaluator.evaluate(expression)); }//end main }//end PostfixEvaluator