0 votes
1 view
in Java by (2.6k points)

I'm trying to write a Java routine to evaluate simple math expressions from String values like:

  • "5+3"
  • "10-40"
  • "10*3"

I want to avoid a lot of if-then-else statements. How can I do this?

1 Answer

0 votes
by (46.1k points)

On JDK1.6, you can try the built-in Javascript algo.

import javax.script.ScriptEngineManager;

import javax.script.ScriptEngine;

import javax.script.ScriptException;

public class Test {

  public static void main(String[] args) throws ScriptException {

    ScriptEngineManager mgr = new ScriptEngineManager();

    ScriptEngine engine = mgr.getEngineByName("JavaScript");

    String foo = "40+2";

    System.out.println(engine.eval(foo));

    } 

}

Related questions

0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 26, 2019 in Java by Nigam (4.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...