Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScriptEngine works in java String, but fails in String[]

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.

like image 822
Soon Avatar asked Sep 30 '22 13:09

Soon


1 Answers

(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/");
like image 183
Joop Eggen Avatar answered Oct 03 '22 14:10

Joop Eggen