import java.util.*; public class PostfixExpressionEvaluater { //Data for all objects private static final String operators = "+-*/"; //Private method private static boolean isOperator(char arg) { return operators.indexOf(arg) != -1; } //Public method public int evaluate(String str) throws ArithmeticException { StackOfIntegers stack = new StackOfIntegers(str.length()); for(int i = 0; i < str.length(); i++) { try { char c = str.charAt(i); int number = -1; if(c >= '0' && c <= '9') { number = 0; while(c != ' ') { number = number * 10 + (c - '0'); i++; c = str.charAt(i); } stack.push(number); System.out.println("Pushed constant " + number); } else if (isOperator(c)) { int x,y,answer=0; y = stack.pop(); System.out.println("Popped the right operand " + y + " of the " + c); x = stack.pop(); System.out.println("Popped the left operand " + x + " of the " + c); switch (c) { case '+': answer = x + y; break; case '-': answer = x - y; break; case '*': answer = x * y; break; case '/': answer = x / y; break; } stack.push(answer); System.out.println("Evaluated " + c +" and pushed "+ answer); } else throw new ArithmeticException("Invalid operator found: " + c); }catch(EmptyStackException e) { throw new ArithmeticException("Not enough numbers in expression!");} }//for if(stack.isEmpty()) throw new ArithmeticException("No expression provided!"); int value = stack.pop(); System.out.println("Popped " + value + " at end of expression."); if (!stack.isEmpty()) throw new ArithmeticException("Not enough operators for all the numbers!"); return value; }//method }//class class TestPostfixExpressionEvaluater { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("To stop testing enter: No more"); System.out.println("Starting..."); while(true) { System.out.print(" Expression: "); String expression = s.nextLine(); if(expression.equals("No more")) { System.out.println("End of test!"); break; } else { try { PostfixExpressionEvaluater w = new PostfixExpressionEvaluater(); System.out.println("Value = "+w.evaluate(expression)); }catch(ArithmeticException e) { System.out.println(e.getMessage()); } } } } } /* 1 2 +7 + 10 5 2 3 +/ 1 2 +++ 1 2 & 10 2 15 3 12 +/*- 2 15 12 -17 *- 1 2 3 4 5 6 7 ++++++ 12 0 / */