Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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 (4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jun 18, 2019 in R Programming by Shubham (3.9k points)
0 votes
1 answer

Browse Categories

...