0

How to calculate a User Input like: 23.5 + 3 *23 within one line? I have tried many ways to loop through the input but can't find any efficient way, to seperate the numbers from the given Operators. PEMDAS can be ignored.

henrymh3
  • 11
  • 1
  • You have to parse the input line, then perform the calculations. Take a look at my [Equation Solver](https://github.com/ggleblanc2/equation-solver) explanation and code to see what's involved. – Gilbert Le Blanc Apr 25 '21 at 20:06

1 Answers1

0

For some simple evaluations you can use a java scripting engine.

Example:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class HelloWorld{

     public static void main(String []args) throws Exception{
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        Double result = (Double) engine.eval("23.5 + 3 *23"); 
        System.out.println(result);
     }
}

But the user can also execute all kinds of java stuff and you should check if your expression is a mathematical formular.

Further solutions can be found here.

Stefan Fenn
  • 483
  • 5
  • 13
  • Wasnt the js engine deprecated and also removed some time ago already? – Zabuzard Apr 25 '21 at 20:20
  • No. The engines had changed from Rhino to Nashorn. But also GraalVM supports the scripting engine api. https://www.graalvm.org/reference-manual/js/ScriptEngine/ – Stefan Fenn Apr 25 '21 at 20:33
  • Well, yes, but GraalVM is not Hotspot. And Nashorn was deprecated in Java 11 and removed with Java 15. See JEP 372. – Zabuzard Apr 26 '21 at 06:29
  • There are many ways to calculate the user input math expression. My Answer is the shortes one I know. Here are some other solutions to this problem https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form – Stefan Fenn Apr 26 '21 at 06:57
  • My point is that your code will not work with current Java versions anymore and you do not even mention this issue. So it is likely that it neither wont help OP nor someone walking by and finding your answer via a search engine. You should mention under which circumstances your answer works and what its disadvantages are. I am just trying to help you to improve the quality of your answer, such that I can upvote it. – Zabuzard Apr 26 '21 at 08:43