How to convert type Object from engine.eval to type int

巧了我就是萌 提交于 2020-01-15 23:04:47

问题


My program takes a String input and calculates it using engine.eval() from ScriptEngine imports. How do I convert the evaluated value to type int?

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

public class Main {

public static void main(String[] args) {

    String s = "206 + 4";
    Object eval;

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine eng = mgr.getEngineByName("JavaScript");

    try {
        eval = eng.eval(s);
    } catch (ScriptException e) {
        System.out.println("Error evaluating input string.");
    }

//Convert Object eval to int sum
}
}

回答1:


You can convert it to a BigDecimal and then get the intValue() from it.

int val = new BigDecimal(eval.toString()).intValue();

Note that intValue() will trim the Decimal in the result. If you want to throw an exception, in case that is happening, use intValueExact() which throws an ArithmeticException.




回答2:


ScriptEngine returns Double for any arithmetic expression, so cast it to Double and use its intValue method

    int res = ((Double) eng.eval(s)).intValue();



回答3:


int i = Integer.valueOf((String) eval);


来源:https://stackoverflow.com/questions/16415888/how-to-convert-type-object-from-engine-eval-to-type-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!