Monday, September 30, 2019

String to Math expression



How to use String into Mathematical Expression or Generating dynamic Math formula from String.



Java 1.6 onward you can use JavaScript engine to convert String into Mathematical expression.

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class MathExpression{
  calcualte() {
    ScriptEngineManager sem= new ScriptEngineManager();
    ScriptEngine scEngine= sem.getEngineByName("JavaScript");
    String formula = "30+50";
    System.out.println(scEngine.eval(formula));
    } 
}





Above code works fine for java. But JavaScript   is not available in Android. so we have to use rhino  in android.


add below entry to gradle dependency.
dependencies {
    implementation 'io.apisense:rhino-android:1.0' 
 }


import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class MathExpression{
  calcualte() {
    ScriptEngineManager sem= new ScriptEngineManager();
    ScriptEngine scEngine= sem.getEngineByName("rhino");
    String formula = "30+20";
    System.out.println(scEngine.eval(formula));
    } 
}





Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...