【发布时间】: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