File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes calculate from String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Groovy Fundamentals video training course this week in the Groovy forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "calculate from String" Watch "calculate from String" New topic

calculate from String

Thomas Rochon
Ranch Hand

Joined: Jul 11, 2002
Posts: 72
Hi there !

You know how to do this :

I've got a String, for example
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)
String s = "2^3+5*3^2+3*4+2";
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!
Thanx ind advance!
- Thomas -
Stefan Krompass
Ranch Hand

Joined: Apr 29, 2004
Posts: 75

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.


Dirk Schreckmann

Joined: Dec 10, 2001
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.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Thomas Rochon
Ranch Hand

Joined: Jul 11, 2002
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 ]
subject: calculate from String