Hanni
Hanni

Reputation: 11

Error: Evaluating a math expression given in string form in Android Studio

I want to evaluate a math expression from a string using Scriptmanager in android studio. I have successfully imported library Jsr223. Now I am able to import following libraries required

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

Now when I do following code

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String foo = "40+2";
ans = engine.eval(foo);

I get error at ans = engine.eval(foo);

unhandled exception : javax.script.ScriptException. ans datatype is int.

Error Image

Using Android Studio 1.5.1 .

Upvotes: 0

Views: 1754

Answers (1)

plainOldNerd
plainOldNerd

Reputation: 305

try 
{
    int ans= (int) engine.eval(foo);
    System.out.printf("%d \n", ans);
} catch (ScriptException e) 
{   e.printStackTrace();   }

This does the job. Notice the try/catch, the int declaration, and the casting to an int.

Upvotes: 1

Related Questions