2016-11-19 87 views
0
package com.cp.javapractice; 

import java.util.ArrayList; 
import java.util.Scanner; 

public class Cp { 
public static void main(String args[]) { 
    ArrayList al = new ArrayList(); 
    Scanner s = new Scanner(System.in); 
    String str = null; 
    str = new String(); 
    System.out.println("Enter the string which you want to remove the  duplicates"); 
    str = s.nextLine(); 
    String arr[] = str.split(" "); 
    for (int k = 0; k < arr.length; k++) { 
     al.add(arr[k]); 
    } 
    try { 
     for (int i = 0; i < arr.length; i++) { 

      for (int j = i + 1; j < arr.length; j++) { 

       if (arr[i].equalsIgnoreCase(arr[j])) { 
        al.remove(j); 
       } 
      } 
     } 
     System.out.println(al); 
     } 
    catch (Exception e) { 
     System.out.println(e); 
    } 
} 
} 

我打算從用戶中替換特定給定字符串中的重複單詞。因此,我使用split方法將給定的字符串與空間分開,並將其放入數組以及arraylist中。循環執行時IndexOutOfBoundsException異常-java

遍歷數組並檢查條件後,它是相等的,然後我刪除了ArrayList中的條件。但是,刪除它顯示索引超出限制例外。

此代碼適用於小數組大小,但在給出大量數組大小時顯示異常。 我有問題,而我給與13個字的數組大小的字符串。

這是我的完整代碼。

+4

這是一個偉大的時間來學習如何使用調試器! – jdigital

+0

您省略了關鍵信息:異常堆棧跟蹤(完整)以及代碼中哪個語句引發異常的指示。請[編輯]您的問題,以包括缺少的信息 –

+0

[IndexOutOfBoundsException]可能的重複(http://stackoverflow.com/questions/4269153/indexoutofboundsexception) – mx0

回答

0
for (int i = 0; i < al.size(); i++) { 

    for (int j = i + 1; j < al.size(); j++) { 

     if (al.get(i).equals(al.get(j)) { 
      al.remove(j); 
     } 
    } 
} 
+0

爲什麼您將其刪除到LowCase轉換代碼? @VojtechRuzicka – PassionInfinite

+0

對不起,我的壞,這是單位,只是想糾正縮進。 –

+0

我檢查了我的編輯,它實際上隻影響縮進。 –

0

例外是因爲您使用的是arr.length而不是al.size()。對於每次移除,數組列表al的大小都會減小。所以,你必須考慮使用arraylist的大小而不是數組的大小。

for (int i = 0; i < al.size(); i++) { // change arr.length to al.size() 

      for (int j = i + 1; j < al.size(); j++) { // change arr.length to al.size() 

       if (arr[i].equalsIgnoreCase(arr[j])) { 
        al.remove(j); 

       } 
      } 
     } 

我建議你檢查出HashSetTreeSet從而降低您刪除重複的努力。


實現在HashSet

import java.util.Arrays; 
import java.util.HashSet; 
import java.util.Scanner; 
import java.util.Set; 


public class Cp { 
public static void main(String args[]) { 

    Scanner s = new Scanner(System.in); 
    String str = null; 
    str = new String(); 
    System.out.println("Enter the string which you want to remove the  duplicates"); 
    str = s.nextLine(); 
    String arr[] = str.split(" "); 

    Set<String> ts = new HashSet<String>(Arrays.asList(arr)); // -> added only this line 

     System.out.println(ts); 

} 
} 
+0

是的!集合將減少處理重複值的工作量。好的建議。 @SkrewEverything – PassionInfinite

+0

它正在工作。謝謝。 – Chitrapandi

+0

@Chitrapandi然後請將答案標記爲已接受並結束問題。 – SkrewEverything

0

問題是你的第二環。開始於i + 1。但我從0到長度-1。所以最後的ein將是j = length-1 + 1,它超出了數組長度。

因此改變第一for循環:

for(int i=0;i < arr.length-2;i++)