0

How can we get the result from a String? For example, if we are given following String

String value = "4 + 5 + - 3";

how can we get the result in int? For exapmple, the answer for the given String is "6".

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Chohan
  • 9
  • 1

1 Answers1

0

You could use a javax.script.ScriptEngine that executes it as js code(or something familiar).

However, there is one big drawback. The ScriptEngine will have the same access as your program. This may be a huge security vulnerability!

Another possibility is to implement it by yourself.

At first, you remove all spaces. Then you look for all non-numerical characters and get the indizes. You parse all sequences of numerical letters to integers. After that, you test (for each non-numeric char) if it is a valid operator. If not, the calculation will be invalid. If it is valid, you execute the belonging operation(you'll have to know the operation and the operators before that step) with the integers before and after the operand. You will have to repeat this(in a loop) until you complete the whole string.

dan1st
  • 12,568
  • 8
  • 34
  • 67