# how to evaluate mathematical expression java



## Abdullah (Feb 16, 2012)

Hi guys ...
I'm working on java project I want to build a calculator where the user enters an String and I should take it and covert it to mathematical expression and do the operations , my question is how do I convert this String and evaluate it to mathematical expression , is there are way to do it on Complex numbers ? 

Thank you a lot..


----------



## xbonez (Feb 17, 2012)

If you're looking to convert strings like this: "2+3x4.5" and "2+(2*4+5)*8" etc into mathematical expressions, you'll have to write a basic parser of your own that expects numbers, decimal numbers, parenthesis, mathematical operators etc and builds a tree like structure that you can then traverse and compute.


----------



## Kreij (Feb 17, 2012)

Yes, you will need some kind of parser and tokenizer so the program understands what to do with the various input characters. You also will have to consider operator precidence and error checking for both invalid characters and valid characters that produce an invalid expression.


----------



## Disparia (Feb 17, 2012)

I suppose for a decent calculator you'll need to do the above. Otherwise you can cheap out and just eval() the expression after replacing x's with *.


----------



## xbonez (Feb 20, 2012)

If you decide to go the Parser route, I would recommend either Coco/R or ANTLR. Both are Parser generators that take a grammar file and generate the required parser. I've personally worked with both (Google Dart uses ANTLR, btw) and like Coco/R for smaller projects. Writing the grammar file will be fairly trivial in your case.


----------



## Dolph (Mar 12, 2012)

I did this for one of my c class projects, it was just a simple calculator, i used a binary tree to sort the expression.  Ex would be like, as you parse the string, if it sees a number, then an operator, it createsthat node with the root ofthe operator, with a series of push/pops onto stacks you eventually create a fully expressed binary tree which when you do an in-order traversal it reads it back as you typed it, and can evaluate it based on depths of the tree for order of operations.  I feel like this method might be alittle complex for an OO language but, for C that was the easiest to do.  The technique coudl still be transferable.


----------

