所以,我一直在努力让这个程序通过这两个测试用例。我应该创建一个列表,其中包含文本中每个非尾部出现的模式后面的字符。
这是代码...
public static ArrayList<Character> getCharsThatFollowPattern (String text, String pattern)
{
ArrayList<Character> character = new ArrayList<Character>();
int i = 0;
while (i <= text.length())
{
int index = text.indexOf(pattern, i);
if (index + pattern.length() < text.length())
{
character.add(text.charAt(index + pattern.length()));
}
i = i + text.indexOf(pattern, index) + pattern.length();
}
return character;
}
以下是测试用例:
a) 对于这个,我得到 [b],但我应该得到 [b, b]
@Test(timeout = 2000)
public void testGetCharsThatFollowPattern ()
{
ArrayList<Character> list = new ArrayList<Character>();
list.add('b');
list.add('b');
ArrayList<Character> chars = PS5Library.getCharsThatFollowPattern("abababa", "aba");
assertEquals(list, chars);
}
b) 对于这个,我得到 [c, d] 但我应该得到 [c, d, c]
@Test(timeout = 2000)
public void testGetCharsThatFollowPattern2 ()
{
ArrayList<Character> list = new ArrayList<Character>();
list.add('c');
list.add('d');
list.add('c');
ArrayList<Character> chars = PS5Library.getCharsThatFollowPattern("abcabdabcab", "ab");
assertEquals(list, chars);
}
最佳答案
按如下方式更改循环:
public static ArrayList<Character> getCharsThatFollowPattern (String text, String pattern) {
ArrayList<Character> characters = new ArrayList<Character>();
int index = text.indexOf(pattern);
while (index >= 0) {
if (index + pattern.length() < text.length()) {
characters.add(text.charAt(index + pattern.length()));
}
index = text.indexOf(pattern, index + 1);
}
return characters;
}
当不再找到该模式时 index
将返回 -1
,因此您可以使用它作为退出循环的检查。
第二个 indexOf()
仅执行 + 1
,因为您期望 abababa
与模式 aba< 重叠
返回 b,b
。
关于java - 测试失败,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150356/