2013-08-01 152 views
0

我正試圖在給定的輸入句子中找到一個單詞的anagrams。這是我運行程序時得到的異常。是否由於列表大小的變化?請幫我解決問題。ArrayList IndexOutOBoundsException從ArrayList中刪除對象後

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 66, Size: 66 
    at java.util.ArrayList.rangeCheck(Unknown Source) 
    at java.util.ArrayList.get(Unknown Source) 
    at MyClass.main(MyClass.java:28) 

這裏是我的源代碼

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
import java.util.Scanner; 

public class MyClass { 

    public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 
     String wordin = sc.nextLine().toLowerCase(); 
     sc.close(); 
     List<String> word = new ArrayList<String>(Arrays.asList(wordin.split("\\s+"))); // splits the whole string into array of words 
     ArrayList<String> sorted = new ArrayList<String>(); 
     int i,j; 
     for (i = 0; i < word.size(); i++) { // loop to sort letters of a particular word 
      word.set(i, word.get(i).replaceAll("[^\\w]", "")); 
      char[] ar = word.get(i).toCharArray(); 
      Arrays.sort(ar); 
      sorted.add(String.valueOf(ar)); // add the sorted word to list 
     } 

     for(i=0;i<sorted.size();i++){ 
      for(j=i;j<sorted.size();j++){ 
       char[] ar = word.get(j).toCharArray(); 
       Arrays.sort(ar); 
       String current = String.valueOf(ar); 
       if(current.equals(sorted.get(i))){ 
        System.out.println(word.get(j)); 
            word.remove(j); 
       } 

      } 


     } 

    } 

} 
+0

什麼是你的輸入? – Tala

+0

您發佈的代碼永遠不會從列表中刪除任何東西... –

+0

這是我的輸入: - 世界各地的部分地區在夏季接近24小時都有陽光。丹在夏天去北極領隊探險。他頭上戴着一根帶子,以表明自己是領導者。 –

回答

3

你的問題是,你遍歷有序集合,並從字列表中刪除。

for(j=i;j<sorted.size();j++){ 
    ... 
    word.remove(j); // and now word is shorter than sorted 
} 

你可能需要有j<word.size()

+0

好吧,我已經遍歷單詞列表,它的工作。謝謝。 –