// **** Imports **** import java.io.*; import java.util.*; /** * Class: TrivialExample5. *
Description: This trivial examples illustrates how to use * the toPrefix(), toInfix(), and toPostfix() mehods. It uses * loop to allow texting multiple expressions. Expressions are * input in infix and then output in all three methods. * This example uses the getValueOf(var, value), setValueOf(var), * buildFromInfix and evaluate() methods. The expression is also * evaluated. * *

* To evaluate prefix or postfix expressions, simply replace "buildFromInfix" by * "buildFromPrefix" or "buildFromPostfix". *

* Requires: *
ExprEvaluator.java *
EasyFormat.java *
DoubleScanner.java * @version Date: 6/10/2008 * @author James Brink, brinkje@plu.edu */ public class TrivialExample5 { double valA, valX, valY; double infixVal; String infix; ExprEvaluator evaluator = new ExprEvaluator(); Scanner scan = new Scanner(System.in); /** * Constructor for TrivialExample5. * * Note: in this case, the expression only uses variables a, x and y. The * values are passed one at time using setValueOf and then the 0 parameter * version of evaluate is used. */ public TrivialExample5() { // get input System.out.print("Enter the value for a: "); valA = scan.nextDouble(); System.out.print("Enter the value for x: "); valX = scan.nextDouble(); System.out.print("Enter the value for y: "); valY = scan.nextDouble(); scan.nextLine(); // read rest of line while (true) { System.out.print("Enter the expression to be evaluated (or press entrer to quit): "); infix = scan.nextLine(); if (infix.trim().equals("")) break; // evaluate expression and print the results try { evaluator.setValueOf('a', valA); evaluator.setValueOf('x', valX); evaluator.setValueOf('y', valY); evaluator.buildFromInfix(infix); System.out.println("The results are"); infixVal = evaluator.evaluate(); System.out.println("a = " + evaluator.getValueOf('a') + ", x = " + evaluator.getValueOf('x') + ", y = " + evaluator.getValueOf('y') + ", expression = " + infixVal); System.out.println("\nThe expression converted to prefix: " + evaluator.toPrefix()); System.out.println("The expression converted to postfix: " + evaluator.toPostfix()); System.out.println("The fully parenthesized infix expression: " + evaluator.toInfix()); }catch (Exception e) { System.out.println ("Error: namely: " + e); } } } // constructor TrivialExample5 /** * Trivial main program that starts the application. */ public static void main (String args[]) { TrivialExample5 app = new TrivialExample5(); System.exit(0); } // end main } // class TrivialExample5