0

I want to make a algebra calculator but I am stack at recibing the user input. How could something like this be done?

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)

1 Answers1

1

Slightly modified answer to a similar question to handle x^n term (where n is a natural number):

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", "$1 * " + 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;
}

Test:

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

Output:

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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42