I'm trying to write a Java routine to evaluate simple math expressions from String
values like:
"5+3"
"10-40"
"10*3"
I want to avoid a lot of if-then-else statements. How can I do this?
I'm trying to write a Java routine to evaluate simple math expressions from String
values like:
"5+3"
"10-40"
"10*3"
I want to avoid a lot of if-then-else statements. How can I do this?
How about something like this:
and do the similar thing for every other mathematical operator accordingly ..
This is actually complementing the answer given by @Boann. It has a slight bug which causes "-2 ^ 2" to give an erroneous result of -4.0. The problem for that is the point at which the exponentiation is evaluated in his. Just move the exponentiation to the block of parseTerm(), and you'll be all fine. Have a look at the below, which is @Boann's answer slightly modified. Modification is in the comments.
You might have a look at the Symja framework:
Take note that definitively more complex expressions can be evaluated:
It's too late to answer but I came across same situation to evaluate expression in java, it might help someone
MVEL
does runtime evaluation of expressions, we can write a java code inString
to get it evaluated in this.I think what ever way you do this it's going to involve a lot of conditional statements. But for single operations like in your examples you could limit it to 4 if statements with something like
It gets a whole lot more complicated when you want to deal with multiple operations like "4+5*6".
If you are trying to build a calculator then I'd surgest passing each section of the calculation separatly (each number or operator) rather than as a single string.
Yet another option: https://github.com/stefanhaustein/expressionparser
I have implemented this to have a simple but flexible option to permit both:
The TreeBuilder linked above is part of a CAS demo package that does symbolic derivation. There is also a BASIC interpreter example and I have started to build a TypeScript interpreter using it.