2016-12-15 13 views
1
public static void main(String[] args) { 
    String[] strArray = { "Islamabad", "Gilgit", "Nawabshah", "Karachi", 
      "Abbotabad", "Gilgit", "Hyderabad", "Islamabad", "Lahore", 
      "Hyderabad", "Sukkur", "Faisalabad", "Kohat", "Faisalabad", 
      "Faisalabad", "Bhakkar", "Faisalabad", "Lahore", "Abbotabad", 
      "Attock", "Karachi", "Rawalpindi", "Nawab Shah", "Abbotabad", 
      "Sukkur", "Attock", "Multan", "Faisalabad", "Multan", "Sukkur" }; 
    System.out.println("Length : " + strArray.length); 

    Arrays.sort(strArray); 

    for (int i = 0; i < strArray.length - 1; i++) { 
     for (int j = i + 1; j < strArray.length; j++) { 
      if ((strArray[i].equals(strArray[j])) && (i != j)) { 
       System.out.println("Duplicate Element is : " + strArray[j]); 
      } 
     } 
    } 

    HashSet<String> set = new HashSet<String>(); 
    for (int i = 0; i < strArray.length; i++) { 
     // If same integer is already present then add method will return 
     // FALSE 
     if (set.add(strArray[i]) == false) { 
      System.out.println("Duplicate element found : " + strArray[i]); 
     } 
    } 
} 

I have tried both methods following this but none of them give any accurate result, it doesn't work for the my number of array elements查找重複的字符串數組中的元素與在Java計數elecment的Occurence

+0

該鏈接使我無處 – nullpointer

+1

它並沒有給我一個@nullpointer –

+1

歡迎堆棧溢出!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –

回答

0

我只想編輯您的代碼,以打印與存在的一個字符串的重複次數:

static int count; 
int i,j; 
for (i = 0; i < strArray.length - 1; i++) { 
     count=0; 
    for (j = i + 1; j < strArray.length; j++) { 
     if ((strArray[i].equals(strArray[j])) && (i != j)) { 
      count++; 
     } 
    } 
System.out.println("Duplicate Element is : " + strArray[j]+"Its occurrences are:"+count); 
} 
+0

不知道如何編譯,因爲在strArray [j]它怎麼知道「j」是什麼? –

+0

實際上j將指向字符串後面的字符串指向由我,例如:如果我=「伊斯蘭堡」然後j指向「吉爾吉特」,現在他們不相等,所以j現在將指向旁邊的字符串「吉爾吉特」,在這種情況下是 - 「Nawabshah」,此後i的值與j的值進行比較,直到數組中的最後一個字符串爲止。 –

+0

我明白了。我的問題是,它如何知道打印語句中的「j」是什麼,因爲j的範圍僅限於前面的大括號。 –

1

如果您正在使用Java 8可以使用StreamCollectors

​​

輸出:

The length of the array is: 30 

Duplicate String Elements and their count is shown below: 
Faisalabad 5 
Gilgit 2 
Islamabad 2 
Hyderabad 2 
Attock 2 
Karachi 2 
Multan 2 
Lahore 2 
Sukkur 3 
Abbotabad 3 

試試吧here!

相關問題