How to replace "x" in string and equate to a number?

Viewed 120

Given a string with only numbers, math operators, and "x", and a number to replace x, how would you replace all x in the string and then equate the string into an answer? So far, I have is this:

String str = "2+4x"; //Example string, could be [2 +4x -  5/ 4 - 9( 6+1*x)] or [4x+0]
Float numToReplace = 20.4; //Has to be Float, cannot use Double


str = str.replace("x", numToReplace);

// How to simplify the string into a number?

I can't equate the string, and I also cannot figure out how to get rid of "implied multiplication" (when the user inputs "2x", I would want to change this to (2*x) in order for the equation to work properly after replacing x).

1 Answers
  1. Replace x after digit(s)
  2. Replace standalone x
String str = "2+4x * x";
float numToReplace = 20.4f;

String expr = str
    .replaceAll("(\\d+)x", "$1 * " + numToReplace)
    .replaceAll("x", Float.toString(numToReplace);

The resulting expression may be evaluated using Nashorn script engine however it is getting deprecated:

public static void main(String ... args) throws ScriptException {
    String str = "2+4x * x";
    float numToReplace = 20.4f;

    String expr = str
        .replaceAll("(\\d+)x", "$1 * " + numToReplace)
        .replaceAll("x", Float.toString(numToReplace);

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

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

    float result = Float.parseFloat(engine.eval(expr));
    System.out.println("result = " + result);
}

Output demonstrating famous floating-point capabilities:

2+4 * 20.4 * 20.4 = 1666.6399999999999
result = 1666.64
Related