// [Rauh 2002] 3. Auflage // evaluation of double value expressions with binary operations only, // given in its postfix notation import java.util.*; // ADT Stack -> pop(), push() // ADT StringTokenizer -> hasMoreTokens(), nextToken() public class Postfixrechner { public Postfixrechner (String delimiters) { stack = new Stack(); // a new empty stack this.delimiters = delimiters; } // Postfixrechner public String rechneAus (String s) { if (s != null && !s.equals("")) { // string to be evaluated is not empty t = new StringTokenizer(s, delimiters); double z1 = 0; double z2 = 0; while (t.hasMoreTokens()) { String token = t.nextToken(); if ((int)token.charAt(0) < 48) { // operator token z1 = ((Double)stack.pop()).doubleValue(); z2 = ((Double)stack.pop()).doubleValue(); if (token.charAt(0) == '+') { // evaluate operator token stack.push(new Double(z2 + z1)); } else if (token.charAt(0) == '-') { stack.push(new Double(z2 - z1)); } else if (token.charAt(0) == '*') { stack.push(new Double(z2 * z1)); } else if (token.charAt(0) == '/') { stack.push(new Double(z2 / z1)); } // if } else { // number token stack.push(new Double(token)); } // if } // while return "" + ((Double)stack.pop()).toString(); // pop the result from the stack } else { // string to be evaluated is empty return "ERROR"; } // if } // rechneAus private String delimiters; private Stack stack; private StringTokenizer t; } // class Postfixrechner