Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formula expression to result [duplicate]

Tags:

java

In Java, if I have a string:

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

How could I get the result of abc = 10?

like image 892
olidev Avatar asked Dec 18 '25 16:12

olidev


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);
    }
}
like image 93
Boris Pavlović Avatar answered Dec 20 '25 06:12

Boris Pavlović


It's not straightforward. You should

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

You can find a simple example in ANTLR documentation: section 2.1 Create a simple grammar, has a Java example with a grammar for basic arithmetic expressions.

like image 34
MarcoS Avatar answered Dec 20 '25 05:12

MarcoS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!