Formula expression for result

In Java, if I have a line:

String abc = "(5)*(2+2)/(2)";

How can I get the result abc = 10?

+3
source share
2 answers
import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        Number number = (Number)engine.eval("(5)*(2+2)/(2)");
        System.out.println("abc = " + number);
    }
}
+8
source

It is not simple. You should

  • have a grammar for arithmetic expressions
  • build lexer / parser from grammar
  • parse your string with the help of a parser and ask the parser to perform semantic actions corresponding to the arithmetic operators of your grammar.

You can find a simple example in the ANTLR documentation : section 2.1 Creating a simple grammar, there is a Java example with a grammar for basic arithmetic expressions.

+1
source

All Articles