/** Program 6.10 The PostfixInterpreter Class That Evaluates a Postfix String */ class PostfixInterpreter { private String postfixString, outputString; /*----------------------------------------*/ private boolean isOperator(char c) { return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^'); }//end isOperator /*----------------------------------------*/ private boolean isSpace(char c) { return (c == ' '); }//end isSpace /*----------------------------------------*/ public void interpretPostfix() { Stack evalStack = new Stack(); double leftOperand, rightOperand; char c; StringTokenizer parser = new StringTokenizer(postfixString,"+-*/^ ",true); while (parser.hasMoreTokens()) { // provided there are more // tokens in the postfixString String token = parser.nextToken(); // get the next token // and let c be c = token.charAt(0); // the first character of this token if ( (token.length() == 1) && isOperator(c) ) { // if token is // an operator rightOperand = ((Double)evalStack.pop()).doubleValue(); leftOperand = ((Double)evalStack.pop()).doubleValue(); switch (c) { // perform the operation case '+': evalStack.push(new Double(leftOperand+rightOperand)); break; case '-': evalStack.push(new Double(leftOperand-rightOperand)); break; case '*': evalStack.push(new Double(leftOperand*rightOperand)); break; case '/': evalStack.push(new Double(leftOperand/rightOperand)); break; case '^': evalStack.push(new Double(Math.exp( Math.log(leftOperand)*rightOperand) ) ); break; default: break; }//end switch } else if ( (token.length() == 1) && isSpace(c) ) { // else if // token was a space ; // ignore it } else { // otherwise, push the numerical value // of the token evalStack.push(Double.valueOf(token)); // on the stack }//end if }//end while // remove final result from stack and output it output("Value of postfix expression = " + evalStack.pop() ); }//end interpretPostfix /*----------------------------------------*/ private void output(String s) { outputString = s; }//end output /*----------------------------------------*/ public void setInput(String input) { postfixString = input; }//end setInput /*----------------------------------------*/ public String getOutput() { return outputString; }//end getOutput /*----------------------------------------*/ }//end class PostfixInterpreter /* insert here the Stack class given either in Program 6.11 or 6.12 */ /*--------------------------------------------------------------------------*/