gpt4 book ai didi

java - 列表数组错误?

转载 作者:行者123 更新时间:2023-12-01 16:08:29 25 4
gpt4 key购买 nike

我正在开发一个项目,该项目需要从服务器拉取并解析 .html 页面,然后解析它的内容。我在字符串中搜索两个值作为单元测试,然后将它们每个保存到列表中,然后将它们与手动创建的 String[] 进行比较。代码如下:

SiteGrabber.java:

//some imports
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;


public class SiteGrabber {

//constructor and java.net stuff

public List<String> getWords(String content){
int prev = 0;
List<String> res = new ArrayList<String>();
String tar = "<tr> <td></td><td><li>";
int tarlen = tar.length();
while(content.indexOf(tar, prev) != -1){
int contentind = content.indexOf("</li>", prev);
if(contentind != -1){
res.add(
content.substring(
content.indexOf(tar, prev) + tarlen,
content.indexOf("</li>", content.indexOf(tar, prev))));
prev = contentind + 5;
}
else{break;}
}
return res;
}

}

SiteGrabberTest.java:

import java.util.List;

import org.junit.Test;

import junit.framework.Assert;

public class SiteGrabberTest {

String htsTest="<tr> <td>List of scrambled words:&nbsp;&nbsp;&nbsp;</td> <td><li>nielle</li></td> </tr><tr> <td></td><td><li>ierneb</li></td> </tr>";
//I want the text between the </td><td><li>...</li> tags.
//2 working tests that show that it sets the List.size() to 0 on a dummy string
//and that it records the right number of results in the List on a valid input.


@Test public void ValidContentTest(){
SiteGrabber myGrabber = new SiteGrabber();
List<String> mylst = myGrabber.getWords(htsTest);

String[] expected = new String[] {"nielle", "ierneb"};
Assert.assertEquals("wrong size", expected.length, mylst.size());
for (int i = 0; i < expected.length; i++) {
Assert.assertEquals("wrong word", expected[i], mylst.get(i));
//breaks on 1st iteration, saying it expects "nielle" and got
//">ierneb", implying some sort of off-by-one error.
}


}
}

最佳答案

更改:

content.indexOf(tar, prev) + tarlen

至:

content.indexOf(tar, prev) + tarlen + 1

关于java - 列表数组错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2079931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com