how to compare elements in a string array in java?

后端 未结 5 1716
予麋鹿
予麋鹿 2021-01-07 12:26

I am trying to find duplicate words in a string array.

Here is my code for the comparison:

   for ( int j = 0 ; j < wordCount ; j++)
   {    
             


        
5条回答
  •  旧巷少年郎
    2021-01-07 13:05

    NullPointerException means that one of your array members is not set (i.e. it is null)

    Don't use == to compare strings.

    You are on the right track - chances are stringArray[] contains some members that are not set. Eacy fix is to null check before using the values.

    for ( int j = 0 ; j < wordCount ; j++)
       {    
           for (int i = wordCount-1 ; i > j ; i--)
           {       
               String wordi = stringArray[i];
               String wordj = strinArray[j];
               // If both are null it won't count as a duplicate.
               // (No real need to check wordj - I do it out of habit)
               if (wordi != null && wordj != null && wordi.compareTo(wordj) == 0 && i!=j)
               {
                   //duplicate
                   duplicates++;
               }
           }
       }
       wordCount -= duplicates;
       System.out.print("\nNumber of words, not including duplicates: " + wordCount);
    

提交回复
热议问题