Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!

calculate from String

Thomas Rochon
Ranch Hand
Posts: 72
Hi there !

You know how to do this :

I've got a String, for example
<code>
String s = "5.0-4.0*(2.0+2.0)+0.0*(2.0+2.0)*(2.0+1.0)+1.0*(2.0+2.0)
*(2.0+1.0)*(2.0-1.0)";
or
String s = "2^3+5*3^2+3*4+2";
</code>
Is there a way to calculate the result of the term, given by the String?
I tried Double d = new Double(s) and I got a NumberFormatException.

If you don't have an idea how to solve this with the Java standart lib,
do you know a free math lib that can handle String terms?

I would be very happy to receive some comments!
- Thomas -

Stefan Krompass
Ranch Hand
Posts: 75
Hi,

what you need, is a math expression parser. The grammar for simple arithmetic expression looks something like this:

The next step is to write a scanner that splits your input into tokens:

The last step is to write the parser-class that tests if your input string is "well-formed" and builds the abstract syntax tree with which you can evaluate your formula. For each rule of your grammar you implement a method. Each of these methods returns a node of the abstract syntax tree. Each node has a method (e.g. evaluate()) which helps you to evaluate the formula. The evaluate()-method of a "plus-node" might something like this:
. To evaluate the entire formula, you call the evaluate()-method of the root of your abstract syntax tree.

HTH

Stefan

Dirk Schreckmann
Sheriff
Posts: 7023
To be clear...

Is there a way to calculate the result of the term, given by the String?

The J2SE API provides nothing to do this automatically.

Thomas Rochon
Ranch Hand
Posts: 72
Thanx, Dirk & Stefan!

Your replies helped me a lot!
At first I was a bit disappointed to read that my problem couldn't
be solved that easy by the J2SE.

But Stefan gave me the solution by telling me what I was searching for:
a java "math expression parser" !

The rest of the job was done by Google
I found JEP from Singular Systems, offering a Java Math Expression Parser
withtwo different licenses, fitting my needs.

Thanx to both of you! You did me a great favor!

Best regards!
- Thomas -
[ May 23, 2004: Message edited by: Thomas Rochon ]