简体   繁体   中英

What's wrong with this group method? (split String)

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));
    }

}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM