// RpnCalculator evaluates reverse Polish expressions. // Uses a stack to store and supply operands to operations // as they are encountered in the input. import java.io.*; import structure.*; import com.mw.io.*; public class RpnCalculator { static boolean isOperator (String M) { if ( M.equals("+") || M.equals("-") || M.equals("*") || M.equals("/") ) return true; else return false; } static void showError (String message) { System.out.println("Error: " + message); } public static void main (String args[]) { SystemInput sysIn = new SystemInput(); ReadStream r = new ReadStream(); Stack S = new StackList(); String nextWord; int i; Integer p1, p2; System.out.println("Enter a Polish expression, followed by cmnd-D"); nextWord = r.readString(); while (! r.eof()) { // Show stack contents after each step. System.out.println(nextWord + " " + S.toString()); // Push operands onto the stack. if (!isOperator(nextWord)) S.push(new Integer(nextWord)); // Handle operators on a FIFO basis. else if (S.size() >= 2) { p2 = (Integer)S.pop(); p1 = (Integer)S.pop(); if (nextWord.equals("+")) S.push(new Integer (p1.intValue() + p2.intValue())); else if (nextWord.equals("-")) S.push(new Integer (p1.intValue() - p2.intValue())); else if (nextWord.equals("*")) S.push(new Integer (p1.intValue() * p2.intValue())); else if (nextWord.equals("/")) S.push(new Integer (p1.intValue() / p2.intValue())); else showError("Invalid operator"); } else showError("Stack has too few operands"); nextWord = r.readString(); } if (S.size() == 1) System.out.println("Final result = " + (Integer)S.pop()); else showError("Expression has too few operators"); } }