The following code do the calculation for data in String rani=String rani = "32*0.25"; and gives the correct output as 8.0
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class StringMathEngine {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String rani = "32*0.25";
System.out.println(engine.eval(rani));
}
}
But fails when it is employed in the following code:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class StringMathEngine {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String[]rani = {"s", "32*0.25", "r", "32*0.75+16", "r", "16", "s", "32"};
for(int n=0;n<rani.length; n++){
if(rani[n].equals("s")) {
rani[n]=rani[n].replaceAll("s","C/");
}
else if(rani[n].equals("r")){
rani[n]=rani[n].replaceAll("r","D/");
}
else {
rani[n]=engine.eval(rani[n]);
}
System.out.println(rani[n]);
}
}
}
Being new to programming I need help to correct this code.
(Initially there was a missing semicolon.)
The problem was that ScriptEngine.eval(...)
returns an Object
, and there is a System.out.println(Object)
. However assigning the object to a String
gives an appropiate error.
for (int n=0; n < rani.length; n++) {
if (rani[n].equals("s")) {
rani[n] = rani[n].replace("s","C/");
} else if(rani[n].equals("r")) { // ('else' missing)
rani[n] = rani[n].replace("r","D/");
} else {
rani[n] = engine.eval(rani[n]); // Semicolon missing!
try {
rani[n] = String.valueOf(engine.eval(rani[n]));
} catch (ScriptException e) {
e.printStackTrace(System.out);
}
}
System.out.println(rani[n]);
}
Alternatively you might use variables:
engine.put("s", "C/");
engine.put("r", "D/");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With