java – How to calculate the value of an expression represented by a string and output it?

Question:

The thing is that I need to solve problems that have a String data type

For instance:

String bla = "5 + 10 - 5";
SystemOutPrintln(Integer.parseInt(bla));

I need to get an answer like 10 . But, the option above will throw an error, since the characters + and - are not integers.

How can I solve this kind of problem, or are there other options, I will be grateful for practical advice?

Answer:

Several solutions are possible:

  1. Write your own interpreter
  2. Connect a ready-made interpreter, for example exp4j
  3. Connect ScriptEngine like JavaScript (use case https://stackoverflow.com/a/3423360/690987 )
  4. Convert expression to java code (on the fly), compile and execute it
  5. Generate bytecode using bytecode generation library and execute it like Byte Buddy
Scroll to Top