/* ========================================================== This demo program uses Java's generic Stack class ========================================================== */ import java.util.Stack; import java.util.Arrays; public class RPN { public static int evalRPN(String[] inp) { Stack opStack = new Stack<>(); String s; for ( int i = 0; i < inp.length; i++ ) { s = inp[i]; // Next item in input (as String !) System.out.println(">" + s); if ( s.equals("x") || s.equals("/") || s.equals("+") || s.equals("-") ) { // Symbol is an operator int o2 = opStack.pop(); // Get the last 2 operands int o1 = opStack.pop(); int r = operate(s, o1, o2); // Perform operation opStack.push( r ); // Save result on stack } else // Symbol is an number (i.e.: operand) opStack.push( Integer.parseInt(s) ); // Save it as Integer System.out.println("opStack = " + opStack); } return opStack.pop(); // Return result (was saved on stack) } public static int operate( String op, int o1, int o2 ) { if ( op.equals("x") ) { System.out.println(">>>" + o1 + " * " + o2); return( o1*o2 ); } else if ( op.equals("/") ) { System.out.println(">>>" + o1 + " / " + o2); return( o1/o2 ); } else if ( op.equals("+") ) { System.out.println(">>>" + o1 + " + " + o2); return( o1+o2 ); } else if ( op.equals("-") ) { System.out.println(">>>" + o1 + " - " + o2); return( o1-o2 ); } else return 0; } }