Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string to math equation [duplicate]

Tags:

java

I need to implement function public int eval(String infix) {...} and when I use this like this:

eval("3+2*(4+5)") 

I must receive 21.

The arithmetic expression can contain '+', '*' and parentheses.

So, how can I convert this to math equation? I can't use non-standard libs.

UPDATE: Solution found.

It is 2 way: Polish Notation and using ScriptEngine.


like image 204
JohnDow Avatar asked Dec 01 '12 17:12

JohnDow


People also ask

How do you evaluate a math expression given in string form in Java?

To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.

How do you parse an expression in Java?

Here's how an arithmetic expression is parsed. A pointer is started at the left and is iterated to look at each character. It can be either a number(always a single-digit character between 0 and 9) or an operator (the characters +, -, *, and /). If the character is a number, it is pushed onto the stack.

How do you print an equation in Java?

println(toString()) in display() .


1 Answers

Believe it or not, with JDK1.6, you can use the built-in Javascript engine. Customise to suit your needs.

Make sure you have these imports...

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

Code:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String infix = "3+2*(4+5)";
System.out.println(engine.eval(infix));
like image 110
xagyg Avatar answered Sep 19 '22 01:09

xagyg