// **** Imports ****
import java.io.*;
import java.util.*;
/**
* Class: TrivialExample3.
*
Description: This trivial examples illustrates how to use
* the buildFromInfix and evaluate methods in the ExprEvaluator
* class. This example uses the getValueOf(var, value), setValueOf(var),
* and evaluate() methods.
*
* The techniques in this example are useful * when only a few variables are used. See TrivailExample2 for a class using * evaluate(var) where var is an array of values for all 26 variables. * TrivialExample uses techniques suitable when only the "common" variables * t, x, and y are used. * *
* 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 TrivialExample3 {
double valA, valX, valY;
double infixVal;
String infix;
ExprEvaluator evaluator = new ExprEvaluator();
Scanner scan = new Scanner(System.in);
/**
* Constructor for TrivialExample3.
*
* 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 TrivialExample3() {
// 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
System.out.print("Enter the expression to be evaluated: ");
infix = scan.nextLine();
// 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);
}catch (Exception e) {
System.out.println ("Error: namely: " + e);
}
} // constructor TrivialExample3
/**
* Trivial main program that starts the application.
*/
public static void main (String args[]) {
TrivialExample3 app = new TrivialExample3();
System.exit(0);
} // end main
} // class TrivialExample3