1. 程式人生 > >Java 字串轉成運算公式

Java 字串轉成運算公式

轉載自:https://www.cnblogs.com/cocoat/p/6956610.html
GroovyShell 實現
public static void main(String args[]) {

        Binding binding = new Binding();

        binding.setVariable("F",2.5);
        binding.setVariable("T",30);
        binding.setVariable("A",100);
        binding.setVariable("P0",100);

        binding.setVariable("language", "Groovy");

        GroovyShell shell = new GroovyShell(binding);

        Object F1 =shell.evaluate("P1=(1+0.1 * (F/100) * T)*P0; return P1 ");

        Object F2 =shell.evaluate("P1=P0*(0.055*0.20+1.0011)+A; return P1 ");

        System.out.println(F1);
        System.out.println(F2);

    }
<dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.7</version>
</dependency>
ScriptEngine實現
public static void main(String args[]) {

        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings(); //Local級別的Binding
        String script = "(1+0.1 * (F/100) * T)*P0"; //定義函式並呼叫
        CompiledScript JSFunction = null; //解析編譯指令碼函式
        try {
            JSFunction = compilable.compile(script);
            bindings.put("F", 2.5);
            bindings.put("T", 30);
            bindings.put("A", 100);
            bindings.put("P0", 100);
            Object result = JSFunction.eval(bindings);
            System.out.println(result); //呼叫快取著的指令碼函式物件,Bindings作為引數容器傳入
        } catch (ScriptException e) {
            e.printStackTrace();
        }


    }