import java.util.StringTokenizer; import java.io.*; // for I/O public class ReversePolishTest { static BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in)); static MyStringStack S; public static void main(String[] args) throws IOException { System.out.println ("Please enter an anrithmetic expression in reverse polish notation" + "\nusing only multiplication and addition."); // parse the input and output to the user StringTokenizer tokenizer = new StringTokenizer(keyboard.readLine()); S = new MyStringStack(); //push the expression onto the stack. while (tokenizer.hasMoreTokens()) { S.push(tokenizer.nextToken()); } System.out.println("The result of the expression is " + getExpr(S) + "."); } //pops an expression off of the stack and returns the evaluation of it. public static int getExpr(MyStringStack S) { String op = S.top(); S.pop(); if (op.equals("+")) { int a = getExpr(S); int b = getExpr(S); return a + b; } else if (op.equals("*")) { int a = getExpr(S); int b = getExpr(S); return a*b; } else return Integer.valueOf(op).intValue(); } }