这组方法有什么问题? (拆分字符串)

时间:2017-10-04 22:39:46

标签: java android regex string

有人可以帮我解决这个递归函数:

输入一个字符串=“5.5 + 33 + 22”;

正则表达式分割第一个数字+运算符=“5.5 + 33”并计算求和或减法。在结果值上调用递归调用+仍处理的字符串部分:“38.5 + 22”

我收到此错误: 我觉得组方法有问题,但我没有设法解决它

  

致命的例外:主要                                                                           过程:com.example.marco.calcol,PID:9798                                                                           java.lang.ArrayIndexOutOfBoundsException:length = 2;索引= 2                                                                               在java.util.regex.Matcher.group(Matcher.java:370)                                                                               在com.example.marco.calcol.MainActivity.compute(MainActivity.java:138)                                                                               在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));
    }

}

2 个答案:

答案 0 :(得分:0)

您的正则表达式中没有捕获组,因此group(1)无效。如果您想要整场比赛,请使用group()group(0)

答案 1 :(得分: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);
}

(?: ... )是非捕获组,不计入m.group(i)。 使用普通组(...),您可以立即提取已识别的元素。