java中如何直接运算数学表达式

走着路睡觉
  • java
小于 1 分钟

JAVA中如何直接运算下面的数学表达式

  1. "5+3"
  2. "10-40"
  3. "(1+10)*3"
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Test {
  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String foo = "40+2";
    System.out.println(engine.eval(foo));
    } 
}
上次编辑于:
贡献者: zhaojingbo
Loading...