Perhaps there is a special function in Java (out of the box, or from libraries), similar to the eval function from languages ​​such as PHP and JS ?

For example, given:

 a="5+3"; 

Function execution:

 return eval(a); // Вернёт 8 

My searches for such a function, among other functions in various official libraries, have led to nothing

Transferred from meta.ru.stackoverflow.com 20 Sep '16 at 17:12 .

This question was originally posted on the discussion forum, support and innovations for the site programmers.

1 answer 1

Java from the box does not know how, because it is in Java, IMHO, is not necessary. But you can run JavaScript java, but he already knows it :

 import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; public class Test { public static void main(String[] args) throws Exception{ ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String foo = "40+2"; System.out.println(engine.eval(foo)); } } 

Or try libu js-evaluator-for-android

We connect

build.gradle project file:

 allprojects { repositories { jcenter() maven { url "https://jitpack.io" } } } 

build.gradle app module file:

 dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) // Keep you existing dependencies here compile 'com.github.evgenyneu:js-evaluator-for-android:v1.0.7' } 

We use:

 JsEvaluator jsEvaluator = new JsEvaluator(this); jsEvaluator.evaluate("2 * 17", new JsCallback() { @Override public void onResult(final String result) { // Process result here. // This method is called in the UI thread. Log.d("MyTag", result); } }); 
  • how to run it? Such a library is not imported, do you need to download it? - Egor Randomize
  • @EgorRandomize, perhaps, the first option in android and will not roll. See another option in the addendum answer. But in general - why do you need to solve such a problem on an adroid in Java? - YurySPb
  • at work they require knowledge of Java, a multi-effect calculator would be an excellent demonstration) - Egor Randomize
  • one
    @EgorRandomize, well, in this way, you can’t demonstrate any special knowledge of Java) Try searching the calculator questions on the site - it seems like there were norms for answers like they are straightforward in Java, without JS - YuriySPb
  • thank you There was a question off topic: I can not declare JSONObject , code JSONObject sa = new JSONObject(); - gives a Stub! - Egor Randomize