2013-02-20 55 views
7

通過使用Jsoup我從網站解析HTML以填充ArrayList與我需要從網站獲取的內容。所以現在我有一個充滿了字符串的ArrayList。我想查找包含某個字符串的列表中的索引。例如,我知道列表中的某個地方,在某些索引中,有字符串(文字)「Claude」,但我似乎無法制作任何代碼,可以找到「Claude」在ArrayList中的索引...這裏是我試過,但返回-1(未找到):在包含字符串的ArrayList中查找索引

ArrayList <String> list = new ArrayList <String>(); 
String claude = "Claude"; 

Document doc = null; 
try { 
    doc = Jsoup.connect("http://espn.go.com/nhl/team/stats/_/name/phi/philadelphia-flyers").get(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
for (Element table: doc.select("table.tablehead")) { 
    for (Element row: table.select("tr")) { 
     Elements tds = row.select("td"); 
     if (tds.size() > 6) { 
      String a = tds.get(0).text() + tds.get(1).text() + tds.get(2).text() + tds.get(3).text() + tds.get(4).text() + tds.get(5).text() + tds.get(6).text(); 

      list.add(a); 

      int claudesPos = list.indexOf(claude); 
      System.out.println(claudesPos); 
     } 
    } 
} 
+3

是'Claude'更大的字符串,或者在它自己的列表中的一個字符串的一部分? – 2013-02-20 06:29:15

+0

嘗試打印字符串'a'並檢查「Claude」。它不應該在那裏。研究如何使用JSoup迭代html標記 – LGAP 2013-02-20 06:31:24

+0

如果將「Claude」添加到列表中,我看不出有-1的理由。插入時要注意額外的空間,可以在插入前使用trim。案件也很重要,「克勞德」與「克勞德」不同。 – sudmong 2013-02-20 06:34:43

回答

25

你混淆String.indexOfList.indexOf。考慮以下列表:

list[0] = "Alpha Bravo Charlie" 
list[1] = "Delta Echo Foxtrot" 
list[2] = "Golf Hotel India" 

list.indexOf("Foxtrot") => -1 
list.indexOf("Golf Hotel India") => 2 
list.get(1).indexOf("Foxtrot") => 11 

所以:

if (tds.size() > 6) { 
    // now the string a contains the text of all of the table cells joined together 
    String a = tds.get(0).text() + tds.get(1).text() + tds.get(2).text() + 
     tds.get(3).text() + tds.get(4).text() + tds.get(5).text() + tds.get(6).text(); 

    // now the list contains the string 
    list.add(a); 

    // now you're looking in the list (which has all the table cells' items) 
    // for just the string "Claude", which doesn't exist 
    int claudesPos = list.indexOf(claude); 
    System.out.println(claudesPos); 

    // but this might give you the position of "Claude" within the string you built 
    System.out.println(a.indexOf(claude)); 
} 

for (int i = 0; i < list.size(); i += 1) { 
    if (list.get(i).indexOf(claude) != -1) { 
    // list.get(i).contains(claude) works too 
    // and this will give you the index of the string containing Claude 
    // (but not the position within that string) 
    System.out.println(i); 
    } 
} 
0
First check whether it is an instance of String then get index 

if (x instanceof String) { 
    ... 
} 

for (int i = 0; i < list.size(); i++) { 
    if (list.get(i).getX() == someValue) { // Or use equals() if it actually returns an Object. 
     // Found at index i. Break or return if necessary. 
    } 
} 
相關問題