Hi basically I need help java and my program is an calculator which must be able to calculate arbitrary expressions like for example (5.0+8.1)*(2.0). My program works fine it does basic things like calling upon classes etc it's just I don't know how to do the arbitrary expressions. My calculator so far does all the basic things such as addition/subtraction/multiplication and division, but it must do arbitrary expressions.

I don't have to do system.input it just a program that tests calculations.

Any suggestions on how I can link them up?

Recommended Answers

I don't know how to do the arbitrary expressions

There is a lot of literature that discusses how to parse expressions. This is a topic some people spend weeks studying when learning to write compilers.
Perhaps you can get an algorithm from Google or Wikipedia.

Jump to Post

All 4 Replies

I don't know how to do the arbitrary expressions

There is a lot of literature that discusses how to parse expressions. This is a topic some people spend weeks studying when learning to write compilers.
Perhaps you can get an algorithm from Google or Wikipedia.

I would suggest looking at Reverse Polish Notation, which is what most calculators use.

Basically, it converts an expression into RPN, a form where all operators come after operands, (postfix) as opposed to in between.

Wikipedia shows how a stack data structure can be effectively utilised for this.

http://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm

If your expression contains only { (,),digits,*,+,/,- } then you can use the "Javascript" Engine. Your choice...

But I do recommend what others have said. Convert the expression to Postfix and then use a stack to evaluate the expression. That way it would be a fun and joyful experience doing this. Good luck!!

lol thanks guys it did help, it sure as hell wasn't fun trying it but when I got it done and working I've earned a nice german beer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.