0

I want to create a method in Java that receives a string equation, for example: "3+2" or "32-1/3" or even "min(32,21)" and returns the result I have found ScriptEngine that offers the solution for simple operations :

ScriptEngineManager mgr = new ScriptEngineManager();
 ScriptEngine engine = mgr.getEngineByName("JavaScript");
 java.lang.String result;
 result = engine.eval(equation).toString();

But it has no min(),max() functionality, and also it's not secure because you can input malicious scripts through.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    Since this is a JavaScript engine, it should have `Math.min` and `Math.max`. – kshetline Oct 28 '19 at 23:12
  • You can use all java too, define variables and functions. A pure java solution would be **`JShell`**. Like the scripting engine `JShell.create().eval("1+3"):`. Note https://stackoverflow.com/questions/57663086/how-to-create-jshell-programmatically-when-securitymanager-is-set – Joop Eggen Oct 29 '19 at 17:19

2 Answers2

1

I found a great library , I just provide a string math equation and it solves it and offers lots of other functionalities.

It's called mxParser by Mariusz Gromada.

import  org.mariuszgromada.math.mxparser.*;
import  org.mariuszgromada.math.mxparser.Constant;

  Constant mp = new Constant("mp",0.5);
        String mpString = Double.toString(mp.getConstantValue());
        String equation = "min(max(1,6)," + mpString +")";
        Expression e = new Expression(equation);
        System.out.println(e.calculate());
0

Comment from @kshetline should solve your problem regarding arithmetic expression question; as for security all I can think of would be using some framework for input sanitization, or write up your own implementation.

Check out How best to sanitize input in Java webapp.

Hope this helps.

hydroPenguin
  • 66
  • 1
  • 4