This question already has an answer here:
-
How to evaluate a math expression given in string form? [closed]
24 answers
Is there a way in Java to get the result from this mathematical expression:
String code = \"5+4*(7-15)\";
In other hand what\'s the best way to parse an arithmetic expression?
You can pass it to a BeanShell bsh.Interpreter
, something like this:
Interpreter interpreter = new Interpreter();
interpreter.eval(\"result = 5+4*(7-15)\");
System.out.println(interpreter.get(\"result\"));
You\'ll want to ensure the string you evaluate is from a trusted source and the usual precautions but otherwise it\'ll work straight off.
If you want to go a more complicated (but safer) approach you could use ANTLR (that I suspect has a math grammar as a starting point) and actually compile/interpret the statement yourself.
i recently developed a expression parser and released it under the apache license. you can grab it at http://projects.congrace.de/exp4j/index.html
hope that helped
You can use the ScriptEngine class and evaluate it as a javascript string
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(\"js\");
Object result = engine.eval(\"5+4*(7-15)\");
Indeed , yu should know that the result of the following instruction in javascript :
eval(\'var aa=5+4*(7-15)\')
aa // -27
There may be a better way, but this one works.
Probably not in as straight forward a manner as you are hoping!
But perhaps you could use a javax.script.ScriptEngine and treat the string as a ECMAScript expression, for example?
Take a look at: Scripting for the Java Platform.
There is no builtin way of doing that. But you can use one of the many many open source calculators available.
Recently I was using very mature math expression parser library, open source, giving the same API for JAVA and .NET. The library name is mXparser. mXparser provides basic functionalities (simple formulas parsing and calculation) and more advanced ones (i.e. user defined arguments, functions). Additionally it is worth to notice that mXparser has rich built-in math collection (meaning operators, unary / binary / variadic functions, iterated operators such as summation and product).
http://mathparser.org/
http://mathparser.org/mxparser-tutorial/
Please find below a few examples to have more clear view on the syntax.
Example 1 - simple formula
Expression e = new Expression(\"2+3\");
double v = e.calculate();
Example 2 - built-in function
Expression e = new Expression(\"2+sin(3)\");
double v = e.calculate();
Example 3 - built-in constants
Expression e = new Expression(\"2+sin(pi)\");
double v = e.calculate();
Example 4 - user defined arguments and constants
Argument x = new Argument(\"x = 5\");
Constant a = new Constant(\"a = 2 + sin(3)\");
Expression e = new Expression(\"a + x^2\", x, a);
double v1 = e.calculate();
x.setArgumentValue(10);
double v2 = e.calculate();
Example 5 - user defined functions
Function f = new Function(\"f(x,y) = x^2 + cos(y)\");
Expression e = new Expression(\"f(10,pi) - 3\", f);
double v = e.calculate();
Example 6 - user defined recursion
Function factorial = new Function(\"fact(n) = if( n > 0; n*fact(n-1); 1)\");
Expression e = new Expression(\"fact(10) - 10!\", factorial);
double v = e.calculate();
Best regards,
LK
There is no direct support in the Java SDK for doing this.
You will either have to implement it yourself (possibly using a parser generator such as JavaCC), or use an existing library.
One option would be JEP (commercial), another JEval (free software).
There\'s a commercial tool called formula4j that does that job.
To take your example expression, it would be evaluated like this using formula4j:
Formula formula = new Formula(\"5+4*(7-15)\");
Decimal answer = formula.getAnswer(); //-27
You coul use that project
How to use:
double result = 0;
String code = \"5+4*(7-15)\";
try {
Expr expr = Parser.parse(code);
result = expr.value();
} catch (SyntaxException e) {
e.printStackTrace();
}
System.out.println(String.format(\"Result: %.04f\", result));
public static int calc(String string){
int result=0;
String numbers=\"0123456789\";
String operations=\"+-/*\";
for (int i=0;i<string.length();i++){
if (numbers.contains(string.charAt(i)+\"\")){
result=result*10+(Integer.parseInt(string.charAt(i)+\"\"));
}
else {
if (string.charAt(i)==\'+\'){ result+=calc(string.substring(i+1));}
if (string.charAt(i)==\'-\'){ result-=calc(string.substring(i+1));}
if (string.charAt(i)==\'*\'){ result*=calc(string.substring(i+1));}
if (string.charAt(i)==\'/\'){ try{result/=calc(string.substring(i+1));}
catch (ArithmeticException e){
System.err.println(\"You cannot devide by Zero!\");}
}
break;
}
}
return result;
}