1

someone can help me with this recursive function:

take in input a string="5.5+33+22";

the regex split the first numbers + the operator = "5.5+33" and calculate the sum or subtraction. The recursive call is called on the result value + the string part still to process: "38.5+22"

i got this error: i guess something wrong with the group method, but I did not manage to solve it

FATAL EXCEPTION: main Process: com.example.marco.calcol, PID: 9798 java.lang.ArrayIndexOutOfBoundsException: length=2; index=2 at java.util.regex.Matcher.group(Matcher.java:370) at com.example.marco.calcol.MainActivity.compute(MainActivity.java:138) at com.example.marco.calcol.MainActivity$14.onClick(MainActivity.java:107) ........

 public void compute(String displ) {
    Pattern p = Pattern.compile("^\\d+(?:\\.\\d+)?[+-]\\d+(?:\\.\\d+)?");
    Matcher m = p.matcher(displ);
    if (m.find()) {
        String s = m.group(1);     // CRASH HERE row(MainActivity.java:138)
        if (s.indexOf('+') >= 0) {
            int index = s.indexOf('+');
            Double a = Double.parseDouble(s.substring(0, index - 1));
            Double b = Double.parseDouble(s.substring(index + 1, s.length()));
            this.sum = this.sum + a + b;
        }
        if (s.indexOf('-') > 0) {
            int index = s.indexOf('-');
            Double a = Double.parseDouble(s.substring(0, index - 1));
            Double b = Double.parseDouble(s.substring(index + 1, s.length()));
            this.sum = this.sum + a - b;
        }
        displ.substring(s.length());

        compute(Double.toString(sum).concat(displ));
    }

}
Marco
  • 15
  • 1
  • 5

2 Answers2

1
public void compute(String displ) {
    Pattern p = Pattern.compile("(\\d+(?:\\.\\d+)?)([+-])(\\d+(?:\\.\\d+)?)");
    for (;;) {
        Matcher m = p.matcher(displ);
        if (!m.find()) {
            break;
        }
        double lhs = Double.parseDouble(m.group(1));
        String op = m.group(2);
        double rhs = Double.parseDouble(m.group(3));
        double result = 0;
        switch (op) {
        case "+":
            result = lhs + rhs;
            break;
        case "-":
            result = lhs - rhs;
            break;
        }
        displ = displ.substring(0, m.start())
            + result
            + displ.substring(m.end());

    }
    System.out.println(displ);
}

(?: ... ) is a non-capturing group, not counted as m.group(i). Using normal groups (...) you can immediately extract the recognized elements.

Joop Eggen
  • 96,344
  • 7
  • 73
  • 121
  • 1
    ok i understand thanks, just a little error: the second double should be "m.group(3)". ps: now i can't rep u, I'm under 15 reputation point – Marco Oct 05 '17 at 16:36
0

There are no capturing groups in your regex, so group(1) is invalid. If you want the entire match, use group() or group(0).

shmosel
  • 42,915
  • 5
  • 56
  • 120