Java で文字列式の値を計算する方法

Javaでは、文字列式の値を計算するためにScriptEngineクラスを使用できます。次に簡単な例を示します。

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

public class Main {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        String expression = "2 + 3 * 4 - 6 / 2";
        try {
            Object result = engine.eval(expression);
            System.out.println(expression + " = " + result);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

この例ではScriptEngineManagerを使用してScriptEngineであるJavaScriptエンジンを取得します。次に計算したい文字列式をexpression変数に代入します。続いてeval()メソッドを使用して式の値を計算し、結果を出力します。

上記コードを実行すると、出力結果は次のようになります。

2 + 3 * 4 - 6 / 2 = 10.0

この方法で私たちは文字列式の値を計算することに成功しました。

bannerAds