// Reverse Polish calculator // A Program demonstrating the use of the stack import java.io.*; import java.util.*; import mystack; class polish { public static void main (String[] args) throws IOException { BufferedReader stdin; stdin = new BufferedReader (new InputStreamReader (System.in)); System.out.print("Type an expression in postfix form: "); StringTokenizer expr = new StringTokenizer(stdin.readLine(), " +-*/", true); String token; Stack s = new Stack(); float a, b; mystack z = new mystack(); while (expr.hasMoreTokens()) { token = expr.nextToken(); switch (token.charAt(0)) { case ' ': // skip the space; break; case '+': a = ((Float)s.pop()).floatValue(); b = ((Float)s.pop()).floatValue(); s.push(new Float(a + b)); break; case '-': b = ((Float)s.pop()).floatValue(); // note the order: pop b, pop a. a = ((Float)s.pop()).floatValue(); s.push(new Float(a - b)); break; case '*': a = ((Float)s.pop()).floatValue(); b = ((Float)s.pop()).floatValue(); s.push(new Float(a * b)); break; case '/': b = ((Float)s.pop()).floatValue(); // note the order: pop b, pop a. a = ((Float)s.pop()).floatValue(); s.push(new Float(a / b)); break; default : s.push(Float.valueOf(token)); break; } if (token.charAt(0) != ' ') { // Print the current toke System.out.print("Token: " + token + "\t"); // and the stack contents z.print_stack(s); } } System.out.println("------------------------------\nThe value is: " + s.pop()); } }