// This simple example shows how to use stack to evaluate // a postfix expression. This implementation is limited // to single digit values, both for operands and for results. // It is easy to expand it to include any integer values, though. // dec-03-1998 import java.io.*; class Expression { static public void main(String[] argv) throws IOException { LStack S = new LStack(); String x, op1, op2, result; BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); String expression; System.out.println(" type a postfix-expression, ending with # "); expression = br.readLine(); int i = 0; x = expression.substring(i,i+1); while (!x.equals("#")) // first read the expression into stack { if (isOperand(x) == true) S.push(x); else { op2 = (String)S.pop(); op1 = (String)S.pop(); result = doOperation(x,op1,op2); S.push(result); } i ++; x = expression.substring(i,i+1); } System.out.println(" result is : " + (String)S.topValue()); } // main static boolean isOperand(String x) { if (x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")) return false; else return true; } // isOperand static String doOperation(String x, String op1, String op2) { int i, j, r; i = Integer.parseInt(op1); j = Integer.parseInt(op2); if (x.equals("+")) return String.valueOf(i+j); else if (x.equals("-")) return String.valueOf(i-j); else if (x.equals("*")) return String.valueOf(i*j); else if (x.equals("/")) return String.valueOf(i/j); return null; } // doOperation }