读取代数函数

Read an algebra function

我想做一个代数计算器,但我一直在接收用户输入。 怎么能做出这样的事情?

String funcion = "X^2 + 3X + 1";
public void calcu(int x){ //code }
int result = calcu(2); //return the value for c = 2 (in this case 11)

稍微修改 answer to a similar question 以处理 x^n 项(其中 n 是自然数):

public static double calcFunction(double arg, String str) throws ScriptException {
    String expr = Pattern.compile("x(\^(\d+))")
        .matcher(str)
        .replaceAll(mr -> "x " + " * x".repeat(Integer.parseInt(mr.group(2))-1)) // x^n
        .replaceAll("(\d+)x", " * " + arg) // ax
        .replaceAll("x", Double.toString(arg));

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

    // a checked ScriptException may be thrown
    System.out.println(expr + " = " + engine.eval(expr));

    double result = Double.parseDouble("" + engine.eval(expr));
    System.out.println("result = " + result);
    return result;
}

测试:

calcFunction(2, "x^2 + 3x + 1");
calcFunction(3, "3x^2 + 3x + 1");

输出:

2.0  * 2.0 + 3 * 2.0 + 1 = 11.0
result = 11.0
3 * 3.0  * 3.0 + 3 * 3.0 + 1 = 37.0
result = 37.0