/*******************************************************************************
*
* Eval program
*
* Purpose: This program asks the user to enter an expression containing only
* literals and then evaluates the expression and displays the
* results.
*
* This program is useful as an aid in learning Operator Precedence
* rules and testing ones understanding and application of the rules.
*
* Notes: The Java programming language has no eval() method which can be
* used to evaluate an expression contained within a string. For this
* reason a JavaScript scripting engine is used and the eval() method
* provided by JS is utilized.
*
* @author Thomas Rogers
*
* @version 1.1 (February 15, 2018)
*
******************************************************************************/
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Eval {
/**=========================================================================
* CLASS main
*
* @param args - The command-line arguments passed to the running program.
*========================================================================*/
public static void main(String[] args) {
// Declare and assign variables
Scanner console = new Scanner(System.in);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
while (true) {
// Get input expression
System.out.print("\nPlease enter an expression to be evaluated or QUIT to exit: ");
String input = console.nextLine();
// See if user wants to quit
if (input.toUpperCase().equals("QUIT")) {
System.out.println("Goodbye!");
break;
}
// Execute expression (which may fail with an exception)
try {
Object result = engine.eval(input);
System.out.println("The result of " + input + " is: " + result);
} catch (ScriptException e) {
System.out.println("Evaluation Error: " + e.getMessage());
} // catch
} // while
} // main
} // class