-1

I have a String that is called for example str="3+5-4+4+5"; i can split it using split(); method but how can i calc more than 2 number like this string

4 Answers4

2

You may try this:

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


String str = "3+5-4+4+5";    
public void myStringCalculation(String str)
{
    ScriptEngineManager x = new ScriptEngineManager();
    ScriptEngine e = x.getEngineByName("JavaScript");
    System.out.println(e.eval(str)); 
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You can do it like this :

  1. Fetch the numbers
  2. Identify the operator
  3. Perform the operation as per the operator for two selected number.
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
0

Look at this SO link - there are ready-to-go parsers out there which will interpret a mathematical expression and return the result of it.

Community
  • 1
  • 1
Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
0

I assume you want to experiment coding.

You might reduce the expression as long as possible using reducible expressions of the form number operator number.

Here a simple version for binary operators, no braces, no negative numbers, only.

String[] operators = new String[] {
    "*", "/",
    "+", "-"
};

String expr = "3+5-4+4+5";

for (;;) {
    boolean reduced = false;
    for (String op : operators) {
        Pattern redex = Pattern.compile("(\\d+)" + Pattern.quote(op) + "(-?\\d+)");
        Matcher m = term.matcher(expr);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            int lhs = Integer.parseInt(m.group(1));
            int rhs = Integer.parseInt(m.group(2));
            int y = 0;
            switch (op) {
            case "*": y = lhs * rhs; break;
            case "/": y = lhs / rhs; break;
            case "+": y = lhs + rhs; break;
            case "-": y = lhs - rhs; break;
            default: throw new IllegalStateException("Not implemented: " + op);
            }
            m.appendReplacement(sb, String.valueOf(y));
            reduced = true;
        }
        m.appendTail(sb);
        expr = sb.toString();
    }
    if (!reduced) {
        break;
    }
}

Negative numbers could function with (negative) look-ahead/behind in the regex.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138