2014-02-22 87 views
0

所以我需要比較兩個不同的ArrayList元素。如果從第一的ArrayList(微博)的元素不匹配任何從第二(井號標籤)我想添加的元素(從微博)在第二的ArrayList(井號標籤)試圖比較兩個不同ArrayList的每個元素

這裏是我的代碼至今:

package edu.bsu.cs121.albeaver; 

import java.util.*; 

public class HashTagCounter { 
    public static void main(String args[]) { 
     System.out 
       .println("Please tweet your tweets,and type 'done' when you are done."); 
     Scanner twitterInput = new Scanner(System.in); 

     ArrayList<String> tweets = new ArrayList<String>(); 
     ArrayList<String> hashTags = new ArrayList<String>(); 

     while (true) { 
      String tweet = twitterInput.next(); 
      tweets.add(tweet); 
      if ("done".equals(tweet)) 
       break; 
     } 

     System.out.println(tweets); 
     twitterInput.close(); 
     int count = 0; 

     for (String tweet : tweets) { 
      if (tweet.contains("#") && count == 0) { 
       hashTags.add(tweet); 
       hashTags.add(1, ""); 
       count++; 
      } else if (tweet.contains("#")) { 
       for (String hashTagged : hashTags) { 
        if (tweet.equalsIgnoreCase(hashTagged) != true) { 
         hashTags.add(hashTagged); 
        } 
       } 
      } 
     } 

     System.out.println(hashTags); 
     System.out.println("Number of unique '#' used is: " 
       + (hashTags.size() - 1)); 

    } 
} 

(編輯)我似乎得到'java.util.ConcurrentModificationException'錯誤。 謝謝你的任何和所有幫助:)

+1

問題是什麼? – Kick

+0

我得到一個'java.util.ConcurrentModificationException' – user3340932

+0

你到目前爲止嘗試過什麼?請發佈一些嘗試和結果,以便我們可以幫助你。 – aliteralmind

回答

1

你得到java.util.ConcurrentModificationException,因爲要修改的ListhashTags當你迭代它。

for (String hashTagged : hashTags) { 
    if (tweet.equalsIgnoreCase(hashTagged) != true) { 
     hashTags.add(hashTagged); 
    } 
} 

您可以創建必須刪除或改進邏輯的臨時項目列表。

2
for (String hashTagged : hashTags) { 
         if (tweet.equalsIgnoreCase(hashTagged) != true) { 
          hashTags.add(hashTagged); 
    -----------------------------^ 
         } 
        } 

問題是迭代hashTags列表時,你不能更新它。