【问题标题】:Pattern Matcher gets ArrayIndexOutOfBoundsException: 0模式匹配器获取 ArrayIndexOutOfBoundsException: 0
【发布时间】:2015-03-07 07:46:48
【问题描述】:

这是我正在尝试做的伪代码:

procedure naive(T, P):
result = { }
for s = 0 to n – m
    match = true
    for j = 0 to m – 1
        if T[s+j] ≠ P[j]
            match = false
    if match
        result = result + {s}

这是我写的:

public class naivepatternmatcher {
    public static Integer[] main(char[] T, char[] P) {
        Integer[] results = {};
        int count = 0;
        boolean match;
        for (int s = 0; s <= (T.length - P.length); s++) {
            match = true;
            for (int j = 0; j <= P.length - 1; j++) {
                if (T[s + j] != P[j]) {
                    match = false;
                }
            }
            if (match == true) {
                results[count] = s;
                count++;
            }
        }
        return results;
    }
}

当我尝试运行我的 Junit 测试类时,我得到一个 ArrayIndexOutOfBoundsException: 0 at "results[count] = s;"在我的主要和“整数 [] 结果 = naivepatternmatcher.main(Sequence, Pattern1);”在我的 Junit 测试中。

public class naivepatternmatcherTest {

private static final char[] Sequence = new char[] { 'a', 'b', 'a', 'a', 'a',
        'b', 'a', 'c', 'c', 'c', 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'a', 'a',
        'b', 'a', 'b', 'a', 'c', 'a', 'a', 'b', 'a', 'b', 'a', 'a', 'c' };

@Test
public void test() {
    char[] Pattern1 = new char[] { 'a', 'a', 'b' };
    Integer[] ShouldEqual = new Integer[] { 3, 10, 17, 24 };
    Integer[] results = naivepatternmatcher.main(Sequence, Pattern1);
    assertArrayEquals(ShouldEqual, results);
}
}

谁能帮我解决这个问题并解释我缺少什么?

【问题讨论】:

  • 或者:Integer[] results = {}; --> Integer[] results = new Integer[T.length - P.length];

标签: java junit pattern-matching indexoutofboundsexception


【解决方案1】:

您的results 是一个固定大小为0 的空数组,results[count] = s 不会将数组的大小增加一并将s 的值附加到它。对于这种动态增长的结果,最好使用ArrayList

另一个建议是,您在内部 for 循环的末尾添加对 break 的调用,因为 if T[s + j] != P[j] 不需要进一步搜索模式的其余部分。

if (T[s + j] != P[j]) {
    match = false;
    break
}

请参阅以下代码以获取保持您的返回类型为Integer[] 并且仅在内部使用ArrayList 的实现示例。

public static Integer[] main(char[] T, char[] P) {
    List<Integer> results = new ArrayList<>();
    boolean match;
    for (int s = 0; s <= (T.length - P.length); s++) {
        match = true;
        for (int j = 0; j <= P.length - 1; j++) {
            if (T[s + j] != P[j]) {
                match = false;
                break;
            }
        }
        if (match == true) {
            results.add(s);
        }
    }
    return results.toArray(new Integer[results.size()]);
}

See it run live

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2017-04-11
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多