问题
I am working in java, and I have to evaluate mathematical expressions given as a String. For example:
"5*8-9/7+5-8"
will result in
35.71.
I tried for "java eval library" , but found no help. Please tell me how to resolve this sort of problem. I can evaluate expression like these using data structure stack or queue but i have to consider operator precedence as multiplication is done prior to subtraction,addition. What data structure will suit this situation best keeping in mind time complexity.
回答1:
From Java 6, you could use the built-in Javascript engine.
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine eng = sem.getEngineByName("JavaScript");
String str = "5*8-9/7+5-8";
System.out.println(eng.eval(str));
Note: The eval()
method throws a ScriptException
and you'll also need the below imports.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
回答2:
Easiest way is to use Java Script Engine. More specifically, the Ecma script (aka Javascript) support, which comes built-in and whose syntax is quite similar to Java.
What you need to do is to retrieve your string using whatever method you want and ask the script engine to evaluate this string.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class X {
public static void main(String[] args) throws ScriptException {
String calculation = "8 * 10 + 3";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Object result = engine.eval(calculation);
System.out.println(result);
}
}
Another option is to build your own DSL. I would recommend Antlr for that. This is waaay harder but will solve your problem.
回答3:
If you do not want to run the javascript engine for the single purpose of evaluating string math expressions, there seem to be others who have had the same problem. Maybe this is an alternative:
http://jeval.sourceforge.net/docs/api/net/sourceforge/jeval/Evaluator.html
来源:https://stackoverflow.com/questions/19926777/expression-evaluation-in-java