2

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).

Dan
  • 3,647
  • 5
  • 20
  • 26
GSDV
  • 43
  • 5

1 Answers1

1
  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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • And then how would I simplify "str" to be a single number? – GSDV Nov 11 '21 at 20:42
  • @GSDV, please check the update – Nowhere Man Nov 11 '21 at 20:51
  • I was able to import the proper stuff, but now my error message is "Cannot convert object to float" for "engine.eval(expr)" (I need to store the value as a float). – GSDV Nov 15 '21 at 19:48
  • @GSDV, you should have called `Float.parseFloat(engine.eval(expr).toString())`, check the update. – Nowhere Man Nov 15 '21 at 20:36
  • Now it says "unreported exception ScriptException; must be caught or declared to be thrown" with an arrow pointing to "expr" – GSDV Nov 17 '21 at 00:03
  • I warned about that in the comment: you're free to declare your method (most likely `main`) throwing the exception, or wrap this invocation into `try-catch` block, you may check the update. – Nowhere Man Nov 17 '21 at 00:15