/* * RPN calculator supporting addition, subtraction and multiplication * of anything that implements the CalculatorOperand interface. * Author Leo Reyzin with minor mods by Wayne Snyder * */ public class RPNCalculator> { EvalStack stack; // the stack holding the operands public RPNCalculator () { stack = new EvalStack(); } /** * Pushes the operand on the calculator stack */ public void operand (T value) { stack.push(value); } /** * Performs an operation on the two topmost elements of the stack * If t1 is topmost and t2 is second topmost, then t1 and t2 will be removed * from the stack and (t2 op t1) will be placed on top of the stack. * Does not modify the stack if it contains fewer than two elements. * @param op operation to be performed */ public void operation (String op) { T op1 = stack.pop(); if (op1 == null) return; T op2 = stack.pop(); if (op2 == null) { stack.push(op1); return; } if(op.equals("+")) op2.addTo(op1); // instead of adding (which only works for numbers) apply generic operation defined by T else if(op.equals("-")) op2.subtractFrom(op1); else if(op.equals("*")) op2.multiplyBy(op1); stack.push (op2); } /** * Prints the calculator stack */ public void print() { if (stack.isEmpty()) System.out.println("Empty stack"); else System.out.println("Stack:\n" + stack.toString()); } }