-1

I have a mathematical expression in the form of a String. String exp = "3 + 6 - 10 + 12 + 15"; Now how to calculate the result of this expression as we do with other mathematical expressions. Help me.

Hanzallah Afgan
  • 716
  • 6
  • 23
Giang Hoàng
  • 11
  • 1
  • 2
  • 3
    you must translate your string in numbers and operators. There is no function for it afaik. Edit: Maybe Script- Engine: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – pL4Gu33 Sep 05 '15 at 14:49
  • Check out [this question](http://stackoverflow.com/q/4589951/2032064) – Mifeet Sep 05 '15 at 14:53

3 Answers3

4

Assuming that there may only be + and - operations, you can remove all the whitespaces and split it to positive and negative integers and sum them.

String expr = "3 + 6 - 10 + 12 + 15";
String[] nums = expr.replaceAll("\\s", "").split("\\+|(?=-)");
int result = Arrays.stream(nums).mapToInt(Integer::parseInt).sum();

If the expressions can be more complex though, including more operators or parentheses, you have to use another solution.

Bubletan
  • 3,833
  • 6
  • 25
  • 33
0

You can use BeanShell bsh.Interpreter for the same:

Interpreter interpreter = new Interpreter(); 
interpreter.eval("result = 5+4*(7-15)");
System.out.println(interpreter.get("result"));

It will evaluate complex mathematical expression.

seahawk
  • 1,872
  • 12
  • 18
-1

Through JDK 1.6 or Higher.

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String expression = "3+6-10+12+15";
    try {
        System.out.println(engine.eval(expression));
    } catch (ScriptException ex) {
        System.out.println("Error occured.");
    }
Hanzallah Afgan
  • 716
  • 6
  • 23
  • 2
    This is prone to [code injection](https://en.wikipedia.org/wiki/Code_injection)... what if this value is taken from user input and they write `txt = "a";while(1){txt = txt += "a";}`? That will crash you. Also, malicious programs could potentially be run. Using Javascript just to calculate some basic arithmetic seems a bit hardcore, anyway. – bcsb1001 Sep 05 '15 at 14:53