import java.util.Stack; /* This file uses the Keyboard class from 101. */ /** * A very small calculator that will handle any expression using the 4 standard * operators. * * @author Robert Sheehan * @version 14/09/2006 */ public class RPNCalculator { public static void main(String[] args) { Stack values = new Stack(); String input; while ((input = Keyboard.readInput()).length() > 0) { try { double number = Double.parseDouble(input); values.push(number); System.out.println(values); } catch (NumberFormatException e) { if (values.size() < 2) { System.out.println("Not enough numbers on the stack."); System.out.println(values); continue; } double x, y; double answer; char operator; if (input.length() > 1) operator = 'z'; // an incorrect operator else operator = input.charAt(0); switch (operator) { case '+': y = values.pop(); x = values.pop(); answer = x + y; break; case '-': y = values.pop(); x = values.pop(); answer = x - y; break; case '*': y = values.pop(); x = values.pop(); answer = x * y; break; case '/': y = values.pop(); x = values.pop(); answer = x / y; break; default: System.out.println("Incorrect operator."); System.out.println(values); continue; } values.push(answer); System.out.println(values); } } } }