import java.util.Stack; class Demo { static int postfixEval(String s) { Stack stk = new Stack(); for (int i = 0; i < s.length(); i++) { char sym = s.charAt(i); if (Character.isDigit(sym)) stk.push(new Integer(Character.digit(sym,10))); else { int rightVal = ((Integer)(stk.pop())).intValue(); int leftVal = ((Integer)(stk.pop())).intValue(); int result = 0; if (sym == '+') result = leftVal + rightVal; else if (sym == '-') result = leftVal - rightVal; else if (sym == '*') result = leftVal * rightVal; else if (sym == '/') result = leftVal / rightVal; stk.push(new Integer(result)); } } return ((Integer)(stk.pop())).intValue(); } static int precedence(char c) { switch (c) { case '+': case '-': return 5; case '*': case '/': return 10; default: throw new IllegalArgumentException(); } } static String infixToPostfix(String infix) { Stack stk = new Stack(); String postfix = ""; for (int i = 0; i < infix.length(); i++) { char sym = infix.charAt(i); if (Character.isDigit(sym)) postfix += sym; else { while (!stk.empty()) { char top = ((Character)(stk.peek())).charValue(); if (precedence(top) < precedence(sym)) break; postfix += top; stk.pop(); } stk.push(new Character(sym)); } } while (!stk.empty()) { char top = ((Character)(stk.pop())).charValue(); postfix += top; } return postfix; } public static void main (String[] args) { System.out.println("postfix: " + args[0]); System.out.println("value: " + postfixEval(args[0])); /* */ /* System.out.println("infix: " + args[0]); System.out.println("postfix: " + infixToPostfix(args[0])); System.out.println("value: " + postfixEval(infixToPostfix(args[0]))); */ /* System.out.println("24+ = " + postfixEval("24+")); System.out.println("24+8* = " + postfixEval("24+8*")); System.out.println("24+8*2/ = " + postfixEval("24+8*2/")); System.out.println("1+2*3 = " + infixToPostfix("1+2*3")); System.out.println("1*2+3 = " + infixToPostfix("1*2+3")); System.out.println("1+2+3 = " + infixToPostfix("1+2+3")); */ } }