I am trying to write a java routine where i can evaluate simple math expression from String for example:
"5+3" or "10-40" or "10*3"
i want to avoid a lot of if then else. any pointer will be helpful - S
I am trying to write a java routine where i can evaluate simple math expression from String for example:
"5+3" or "10-40" or "10*3"
i want to avoid a lot of if then else. any pointer will be helpful - S
This will be lots of fun if you're going to include compound expressions such as (3+4)*(1+2). Maybe use recursion?
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
String math = "1+4";
if (math.split("+").length == 2) {
//do calculation
} else if (math.split("-").length == 2) {
//do calculation
} ...
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.
The correct way to solve this is with a lexer and a parser. You can write simple versions of these yourself, or those pages also have links to Java lexers and parsers.
Creating a recursive descent parser is a really good learning exercise.
With JDK1.6, you can use the built-in Javascript engine.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
}
}