3

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.

Samuel
  • 175
  • 1
  • 1
  • 8

2 Answers2

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
  • 1
    Whoever 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
  • is it a good way to do that? use Javascript inside java? – Mysterion Jan 27 '15 at 15:03
  • 2
    I 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