Search code examples
javascriptengine

Convert division equation (String) into a Double


I am trying to convert a division equation (String) into a double, and then be able to add or subtract from it. Eclipse gives me a "The operator + is undefined for the argument type(s) Object, int" error.

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

public class EVCalc {
  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String ShutterSpeed = "1/50";
    Double.parseDouble(engine.eval(ShutterSpeed).toString());

    System.out.println(engine.eval(ShutterSpeed)+1);
  } 
}

Solution

  • You need to use the return value from Double.parseDouble():

    double parsedValue = Double.parseDouble(engine.eval(ShutterSpeed).toString());
    
    System.out.println(parsedValue + 1);