Is there any way to convert string like "10+(8*9)" in Java to integer (result)? I'm trying to do it by parsing strings to characters looping trought them and somehow trying to get the result but it's really complicated so I'm just wondering if there is any other easier way to do this.
Asked
Active
Viewed 151 times
3
-
There is no easy way. You need an expression parser. One possible option is using the built-in JavaScript engine to evaluate that for you. – Marko Topolnik Jan 27 '15 at 15:02
-
Use the built-in JavaScript engine for such simple mathematical calculations – Konstantin Yovkov Jan 27 '15 at 15:02
-
1the usual approach to this problem is to convert the input into a Reverse Polish notation – njzk2 Jan 27 '15 at 15:02
-
1@MarkoTopolnik - What's wrong with using a Stack and popping operands when operators are encountered? – TheLostMind Jan 27 '15 at 15:05
2 Answers
2
What you have here is an Infix notation
It is very difficult to interpret directly, and is usually converted to RPN or Postfix notation first.
The Shunting-yard algorithm written by Dijkstra does the conversion for you. You should obtain a result that can be represented as:
10 8 9 * +
Once you have this, you apply the postfix algorithm to solve the stack you have.

njzk2
- 38,969
- 7
- 69
- 107
-
1Whoever downvoted this, please justify your vote; this is an excellent answer. – mdl Jan 27 '15 at 15:14
0
Java has the built-in javascript engine - it can evaluate arithmetic expressions for you:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String expression= "10+(8*9)";
System.out.println(engine.eval(expression));
}
}

bedrin
- 4,458
- 32
- 53
-
-
2I wouldn't recommend this without pointing out that you're actually invoking a lot more than an expression parser. This is able to execute arbitrary JavaScript, which is very relevant if the input is user data. – Joachim Sauer Jan 27 '15 at 15:04
-
I've added simple checker if it's a arithmetic expression and it works perfectly, thanks. – Samuel Jan 27 '15 at 15:27