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++)
{
for (int i = wordCount-1 ; i > j ; i--)
{
if (stringArray[i].compareTo(stringArray[j]) == 0 && i!=j)
{
//duplicate
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: " + wordCount);
in the if statement, it says NullPointerException
. What does this mean? Is there a better way to do this? I tried simply doing
if (stringArray[i] == stringArray[j] && i!=j)
but that kept giving me wrong answers.
You can do like this for beter performance:
It means
stringArray[i]
isnull
, i.e. your array has anull
entry in it somewhere. It's possible that you have a logic error elsewhere and some elements of the array are not being set correctly.If your array legitimately contains nulls, you have to explicitly check for this before trying to call methods on
stringArray[i]
:Here i see you are trying to find unique elements count for given string. I would suggest using HashSet for better solution.
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.Null pointer may be because you have any null value in your array.
Your code is not working because you are itrating on same array on which you need to find duplicates
you can use following code to count duplicate words in array.