相关文章推荐

JavaScript eval in JavaApplication: “javax.script.scriptException: Expected operand but found”

java javascript

In my Java Application, Im relying on JavaScript, implemented via ScriptEngine, to interpret and calculate some basic mathequations I read from a String.

Here is what Ive got:

public void calc(String comp){
try {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine eng = mgr.getEngineByName("JavaScript");
            res[k] = (Integer) eng.eval(comp);
        } catch (Exception e){
            System.out.println("Error in res: " +e);

No matter which input, excuting will result in:

Error in res: javax.script.ScriptException: :1:5 Expected an operand but found ,
[3, -, 3]
^ in at line number 1 at column number 5, here with exemplary input comp = "3-3"

Error in public int[] res: javax.script.ScriptException: :1:6 Expected an operand but found *
[-12, *, 3]
^ in at line number 1 at column number 6

I dont know JavaScript so I dont know what to do in order to fix this error.

It looks like the string is a stringified array, so you'll either need to join() the array in JavaScript before you pass it to your Java app, or write some Java code to do so.

Here's the JavaScript code:

var str = [3, '-', 3].join(''); // "3-3"
 
推荐文章