import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; /** Simple calculator using reverse polish notation (RPN). */ public class RPNCalc { /** Stack for storing the operands. */ private final Stack operands = new Stack(); /** Evaluates an expression in RPN given as individual string tokens. */ private void evaluate(String[] args) { for (int i = 0; i < args.length; ++i) { handleToken(args[i]); } if (operands.size() != 1) { System.err.println("Invalid expression!"); } System.out.println(operands.pop()); } /** Handles a single token. */ private void handleToken(String token) { if (token.length() == 1 && operands.size() >= 2) { double op2 = operands.pop(); double op1 = operands.pop(); switch (token.charAt(0)) { case '+': operands.push(op1 + op2); return; case '-': operands.push(op1 - op2); return; case '*': operands.push(op1 * op2); return; case '/': operands.push(op1 / op2); return; } // no operation... operands.push(op1); operands.push(op2); } // must be number then try { operands.push(Double.parseDouble(token)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid token: " + token); } } /** Main method. */ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); String line = null; while ((line = reader.readLine()) != null) { try { new RPNCalc().evaluate(line.split(" +")); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } }