// **** Imports **** import java.io.*; import java.util.*; /** * Class: TrivialExample4. *
Description: This trivial examples illustrates how to use * the user function. *

* Sample run: *

 *   Enter the value for x: 10
 *   Enter the value for y: 20
 *   Enter the value for z: 30
 *   Enter the function beginning with 'define user(':
 *   define user(a, b, x) = x * max(a, b)
 *   Enter the expression to be evaluated:
 *   100000 + user(x, y, z)
 *   The results are
 *   x = 10.0, y = 20.0, z = 30.0, expression = 100600.0
 *
*

* Requires: *
ExprEvaluator.java *
EasyFormat.java *
DoubleScanner.java * @version Date: 6/10/2008 * @author James Brink, brinkje@plu.edu */ public class TrivialExample4 { double valX, valY, valZ; double infixVal; String functionDef; String infix; ExprEvaluator evaluator = new ExprEvaluator(); Scanner scan = new Scanner(System.in); /** * Constructor for TrivialExample4. * * In this example, the user can define and use a function. */ public TrivialExample4() { // get input System.out.print("Enter the value for x: "); valX = scan.nextDouble(); System.out.print("Enter the value for y: "); valY = scan.nextDouble(); System.out.print("Enter the value for z: "); valZ = scan.nextDouble(); scan.nextLine(); // read rest of line try { // read and process the function definition System.out.println("Enter the function beginning with 'define user(': "); functionDef = scan.nextLine(); evaluator.buildFromInfix(functionDef); // read the expression System.out.println("Enter the expression to be evaluated: "); infix = scan.nextLine(); // evaluate expression and print the results evaluator.setX(valX); evaluator.setY(valY); evaluator.setValueOf('z', valZ); evaluator.buildFromInfix(infix); System.out.println("The results are"); infixVal = evaluator.evaluate(); System.out.println("x = " + evaluator.getValueOf('x') + ", y = " + evaluator.getValueOf('y') + ", z = " + evaluator.getValueOf('z') + ", expression = " + infixVal); }catch (Exception e) { System.out.println ("Error: namely: " + e); } } // constructor TrivialExample4 /** * Trivial main program that starts the application. */ public static void main (String args[]) { TrivialExample4 app = new TrivialExample4(); System.exit(0); } // end main } // class TrivialExample3