views:

530

answers:

6

Is there a way in Java to get the result from this mathematical expression:

String code = "5+4*(7-15)";

Ie, what's the best way to parse an arithmetic expression?

+2  A: 

There is no builtin way of doing that. But you can use one of the many many open source calculators available.

soulmerge
+2  A: 

This may be of help: Parsing an Algebraic Expression

ennuikiller
+1  A: 

Probably not in as straight forward a manner as you are hoping!

But perhaps you could use a javax.script.ScriptEngine and treat the string as a ECMAScript expression, for example?

Take a look at: Scripting for the Java Platform.

Andy
That is rather dangerous, as it would allow "script injection" (similar to SQL injection). Proceed with caution.
sleske
Good point. I suppose it depends on what the source of the expressions is.
Andy
A: 

There is no direct support in the Java SDK for doing this.

You will either have to implement it yourself (possibly using a parser generator such as JavaCC), or use an existing library.

One option would be JEP (commercial), another JEval (free software).

sleske
+3  A: 

You can pass it to a BeanShell bsh.Interpreter, something like this:

Interpreter interpreter = new Interpreter();
interpreter.eval("result = 5+4*(7-15)");
System.out.println(interpreter.get("result"));

You'll want to ensure the string you evaluate is from a trusted source and the usual precautions but otherwise it'll work straight off.

If you want to go a more complicated (but safer) approach you could use ANTLR (that I suspect has a math grammar as a starting point) and actually compile/interpret the statement yourself.

Nick Holt
Good idea, but problematic with untrusted input, as it would allow "script injection" (see my other comment).
sleske
@sleske: yeah, you'd certainly have to be careful with injection attacks if the string is user entered.
Nick Holt
this lib is wonderfull!
Martijn Courteaux
Can also use built-in JavaScript (Rhino) interpreter now. Although seems more complex to get an eval. And still have a security risk...
PhiLho
@PhiLho: BeanShell was just something I used a few years ago, but I agree that something based on the `javax.script` API (I think Rhino is) would be better.
Nick Holt
+1 for beanshell, being part of the JRE
Thorbjørn Ravn Andersen
What would this return if the expression were "2/3"? Would it return 0 like Java does? You could stick a typecast in front, but then what about "(2/3)+(1/2)"?
dreeves
A: 

You could use Jython's interpreter for that.

Joonas Pulakka
I don't know the size of Jython, but it looks like a bit of an overkill...
PhiLho
Granted - if the only objective is to calculate "5+4*(7-15)" ;-)
Joonas Pulakka