package net.datastructures; import java.util.*; public class PostFixCalculator { /** * Default constructor */ public PostFixCalculator() { } /** * Evaluates a postfix expression containing Integer operands * @param s is a postfix expression * @return an int giving the value of the expression */ public int evaluate(String s) { Stack stack = new ArrayStack(); StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { String element = st.nextToken(); if (isNumber(element)) { // stack.push(new Integer((Integer.parseInt(element)))); stack.push((Integer.parseInt(element))); } else { ExpressionOperator op; Integer opnd2 = null, opnd1 = null; switch (element.charAt(0)) { // Must be an operator case '+': op = new AdditionOperator(); opnd2 = stack.pop(); opnd1 = stack.pop(); op.setOperands(opnd1, opnd2); stack.push(op.getValue()); break; case '-': op = new SubtractionOperator(); opnd2 = stack.pop(); opnd1 = stack.pop(); op.setOperands(opnd1, opnd2); stack.push(op.getValue()); break; } } } return stack.pop(); } private boolean isNumber(String s) { return Character.isDigit(s.charAt(0)); } public static void main(String args[]) { PostFixCalculator pfc = new PostFixCalculator(); System.out.println(pfc.evaluate("151 60 + 92 -")); } }