/** * CSI3540. Structures, techniques et normes du Web
*
* Uasage:
* In DrJava, System.out.println( RPN.eval( RPN.getRandomExpression() ) );
* From the command line:
* java RPN "9 3 / 10 2 3 * - +" * * @author Marcel Turcotte, Université d'Ottawa/University of Ottawa */ package test; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.Stack; import java.util.Random; public class RPN { public static int eval( String input ) throws IOException { Stack s = new Stack(); StringReader sr = new StringReader( input ); StreamTokenizer st = new StreamTokenizer( sr ); st.eolIsSignificant( false ); // expressions may contain newlines st.ordinaryChar( '/' ); // should not be interpreted as a comment int token = st.nextToken(); while ( token != StreamTokenizer.TT_EOF ) { switch( token ) { case StreamTokenizer.TT_NUMBER: s.push( (int) st.nval ); break; default: int r = s.pop(); int l = s.pop(); int res = 0; switch( st.ttype ) { case '+': res = l + r; break; case '-': res = l - r; break; case '*': res = l * r; break; case '/': res = l / r; break; } s.push( res ); } token = st.nextToken(); } return s.pop(); } public static final int MAXIMUM_DEPTH = 2; public static final double THRESHOLD = 0.5; private static final Random random = new Random(); public static String getRandomExpression() { return getRandomExpression( MAXIMUM_DEPTH ) + " " + getRandomExpression( MAXIMUM_DEPTH ) + " " + getRandomOperator(); } private static String getRandomExpression( int depth ) { String expr; if ( depth == 0 || random.nextDouble() < THRESHOLD ) { expr = getRandomTerminal(); } else { expr = getRandomExpression( depth-1 ) + " " + getRandomExpression( depth-1 ) + " " + getRandomOperator(); } return expr; } private static String getRandomTerminal() { return Integer.toString( random.nextInt( 14 ) + 1 ); } private static String getRandomOperator() { String[] ops = { "+", "-", "*", "/" }; return ops[ random.nextInt( 3 ) ]; // avoids '/' so as to produce integer result } public static void main( String[] args ) throws IOException { System.out.println( args[ 0 ] + " = " + eval( args[ 0 ] ) ); System.out.println( getRandomExpression() ); } }