0

So I'm having a string with input data like String input = "5-3*7+8/6*2" and I want to calculate the result using mathematic calculation rules like * before + and so on... Is there an easy way to kind of sort the single pars of the operation to follow these rules? I allready tried to create substrings with each number and it's operator but I don't know how to proceed from there:

int i_tmp = -1;
for (int i=0; i<string.length(); i++) {
    //ia.getPositionAll() is true if the character i of the string is an operator
    if (ia.getPositionAll()[i]==true) { 
        substrings[i]=string.substring(i_tmp+1, i);
        i_tmp = i-1;
    }
}

Now I don't know how to proceed from this point...

The substrings are like:

substring[0] = 5
substring[1] = -3
substring[2] = *7
substring[3] = +8

substring[n] = etc.

Thank you all, H.

  • separate String char by char and identify which operation needs to be performed using something like `if(char c == "*" ) {` multiply Integers you found `}` – Turtle Sep 20 '15 at 13:33
  • Parse it. Use a stack. – Dave Newton Sep 20 '15 at 13:33
  • Note that if this is homework, then your teachers will probably **not** accept a solution based on the internal Javascript engine which is the accepted answer on the dupe. You should be looking at the other answers. – RealSkeptic Sep 20 '15 at 13:58

1 Answers1

1

You can do it like this:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class A {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    String input = "5-3*7+8/6*2";
    System.out.println(engine.eval(input));
    } 
}
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23