Advertisement
richarduie

FormulaEvaluator.java

May 26th, 2013
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.29 KB | None | 0 0
  1. /*
  2.  * Use the JavaScript Engine to employ calls to the eval() function.
  3.  * This is much simpler than writing a full formula parser and lexer
  4.  * with the capacity to tokenize, substitute, and evaluate general
  5.  * mathematical expressions.
  6.  *
  7.  * Session example:
  8.  * Enter a formula.
  9.  * (y-3.25) / x
  10.  * Enter the value of the variable x:
  11.  * 10.35
  12.  * Enter the value of the variable y:
  13.  * 13.6
  14.  * formula: (y-3.25) / x
  15.  * with variables:
  16.  *    x = 10.35
  17.  *    y = 13.6
  18.  * translates to: (13.6-3.25) / 10.35 and
  19.  * evaluates to: 1.0
  20.  */
  21.  
  22. import java.util.Hashtable;
  23. import java.util.Scanner;
  24. import java.util.Map.Entry;
  25.  
  26. import javax.script.ScriptEngine;
  27. import javax.script.ScriptEngineManager;
  28. import javax.script.ScriptException;
  29.  
  30. public class FormulaEvaluator
  31. {
  32.     public static void main( String[] args ) {
  33.         // Scanner to collect user input
  34.         Scanner scan = new Scanner(System.in);
  35.        
  36.         // prompt user for formula string
  37.         System.out.println( "Enter a formula.");
  38.         String formula = scan.nextLine();
  39.         // variables will be presumed to be single, lower-case
  40.         // alphabetical characters - kill everything else
  41.         String variables = kernel(
  42.             formula.replaceAll( "[^a-z]", "" )
  43.         );
  44.  
  45.         // to collect values or each variable
  46.         String[] values = new String[ variables.length() ];
  47.         // for each lower-case variable name, collect value
  48.         for (int i = 0; i < variables.length(); i++) {
  49.             System.out.println(
  50.                 "Enter the value of the variable " +
  51.                 variables.charAt( i ) + ": "
  52.             );
  53.             values[ i ] = scan.next();
  54.         }
  55.  
  56.         // copy original formula
  57.         String evaluable = formula;
  58.         // substitute the corresponding value for each variable
  59.         // in the original formula
  60.         for (int i = 0; i < variables.length( ); i++) {
  61.             evaluable = evaluable.replaceAll(
  62.                 "" + variables.charAt( i ), values[ i ]
  63.             );
  64.         }
  65.        
  66.         // get script engine manager instance
  67.         ScriptEngineManager manager = new ScriptEngineManager();
  68.         // javascript engine instance to use for evaluation, since
  69.         // math ops are mostly the same
  70.         ScriptEngine engine = manager.getEngineByName("js");        
  71.         Object result = null;
  72.         try {
  73.             result = engine.eval( evaluable );
  74.         } catch (ScriptException e) {
  75.             System.out.println( e.toString() );
  76.         }
  77.        
  78.         // compose output to report
  79.         String rpt = "formula: " + formula + "\nwith variables:";
  80.         for (int i = 0; i < variables.length( ); i++) {
  81.             rpt += "\n   " + variables.charAt( i ) + " = " +
  82.                 values[ i ];
  83.         }
  84.         rpt += "\ntranslates to: " + evaluable + " and " +
  85.             "\nevaluates to: " + String.valueOf( result );
  86.         System.out.println( rpt );
  87.     }
  88.     // Return unique elements of a on first dimension.
  89.     public static String kernel( String s ) {
  90.         // Set hashtable style associative array working storage.
  91.         Hashtable<String, String> r = new Hashtable<String, String>();
  92.         // For each element in s...
  93.         for (int i = 0; i < s.length(); i++) {
  94.             // ...assign key/value pair - repeated values have same key and
  95.             // replace one another, leaving only single instance of value.
  96.             r.put("" + s.charAt( i ), "" + s.charAt( i ));
  97.         }
  98.         // Initialize return.
  99.         StringBuffer sb = new StringBuffer();
  100.         // For each key in r...
  101.         for (Entry<String, String> entry : r.entrySet()) {
  102.             sb.append( entry.getKey() );
  103.         }
  104.         return sb.toString();
  105.     };
  106.  
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement