【发布时间】:2015-06-03 19:17:28
【问题描述】:
我编写的代码使用 jsoup 访问网站,查看所有段落标题,然后将它们保存到名为 headingList 的 ArrayList 中。这是棘手的部分。我有一个将字符串作为键和 ArrayLists 作为值的映射。该代码的设计方式要求它进入多个页面。因此,标题数量以及与标题相关的段落数量可能会有很大差异。所以,这里的想法是创建两个 int 值。一个名为headingAmt 的int 值在它查看页面并确定有多少标题后设置。第二个名为headCount 的int 值被初始化为1。然后我要做的是设置一个像这样的while 循环:while(headCount != headAmt + 1) 并在循环结束时递增它,以便它在@ 时终止987654325@ 遍历每个标题。在 while 循环中,我尝试将每个段落添加到名为 items 的 ArrayList 中,然后获取 items 数组列表中的内容,然后将其设置为地图中第一项的值。然后,清除 ArrayList,转到下一段,将那里的内容保存到 items,然后将该 ArrayList 设置为地图中第二项的值,依此类推。我有我可以发布的代码,但是由于我无法让它正常工作,所以有问题的 while 循环已经重新排列了很多次,这很令人困惑。
如果有人可以提供帮助,请编辑以下代码:
public class Finder {
public Finder(String url) {
String mainURL = "http://www.website.com";
Map<String, List<String> > headMap = new HashMap<>();
ArrayList<String> headingList = new ArrayList<>();
ArrayList<String> items = new ArrayList<>();
int headCounter = 1;
String itemList = "div > div:nth-child(1).category > ul:nth-child(2) > li.item > span";
int headAmt;
Document doc1 = null;
///// Connect to site to get menu /////
try{
doc1 = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36")
.referrer("http://www.google.com")
.get();
}
catch(IOException e){
System.out.println("Can't connect to website");
}
/////// Get headings ////////
Elements head = doc1.select("div > div > div > h3");
////// Loop through headings and add to ArrayList /////
for(Element e: head){
headingList.add(e.text());
}
headAmt = headingList.size();
/*
Here is the problem
*/
while(headCounter != headAmt + 1){
Elements elem = doc1.select("div > div:nth-child("+ headCounter +").category > ul:nth-child(2) > li.item > span");
for (String key : headingList) {
for(Element e : elem){
items.add(e.text());
}
List<String> value = new ArrayList<>(items);
headMap.put(key, value);
}
items.clear();
headCounter++;
}
}
}
}
}
【问题讨论】:
标签: java android arraylist linkedhashmap