//  Data Structures with Java by John R. Hubbard
//  Copyright McGraw-Hill, 2001
//  Example 6.4 on page 112
//  Simulating a RPN calculator

import java.util.Stack;
import java.io.*;

public class Ex0604
{ public static void main(String[] args)
  { boolean quit=false;
    String input;
    double x, y, z;
    Stack operands = new Stack();
    while (!quit)
    { input = getString("RPN> ");
      switch (input.charAt(0))
      { case 'Q':
          quit = true;
          break;
        case '+':
          y = Double.parseDouble((String)operands.peek());
          operands.pop();
          x = Double.parseDouble((String)operands.peek());
          operands.pop();
          z = x + y;
          System.out.println("\t" + x + "+" + y + " = " + z);
          operands.push(new Double(z).toString());
          break;
        case '-':
          y = Double.parseDouble((String)operands.peek());
          operands.pop();
          x = Double.parseDouble((String)operands.peek());
          operands.pop();
          z = x - y;
          System.out.println("\t" + x + "-" + y + " = " + z);
          operands.push(new Double(z).toString());
          break;
        case '*':
          y = Double.parseDouble((String)operands.peek());
          operands.pop();
          x = Double.parseDouble((String)operands.peek());
          operands.pop();
          z = x * y;
          System.out.println("\t" + x + "*" + y + " = " + z);
          operands.push(new Double(z).toString());
          break;
        case '/':
          y = Double.parseDouble((String)operands.peek());
          operands.pop();
          x = Double.parseDouble((String)operands.peek());
          operands.pop();
          z = x / y;
          System.out.println("\t" + x + "/" + y + " = " + z);
          operands.push(new Double(z).toString());
          break;
        default:
          operands.push(input);
       }
    }
  }
  
  private static String getString(String prompt)
  { System.out.print(prompt);
    InputStreamReader iSReader = new InputStreamReader(System.in);
    BufferedReader bReader = new BufferedReader(iSReader);
    String input="";
    try { input = bReader.readLine(); }
    catch(IOException e) { System.out.println(e); }
    return input;
  }
}
