• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.
  • The forums have been upgraded with support for dark mode. By default it will follow the setting on your system/browser. You may override it by scrolling to the end of the page and clicking the gears icon.

how to evaluate mathematical expression java

Abdullah

New Member
Joined
Feb 15, 2012
Messages
1 (0.00/day)
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 ? :confused:

Thank you a lot..
 
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.
 
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.
 
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 *. ;)
 
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.
 
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.
 
Back
Top