Possible Duplicate:
how to compare elements in a string array in java?
I am trying to set the words in an array to a string, and then calculate the number of words not including duplicates, but when I try to check for duplicates with an if statement, it says "NullPointerException" meaning there is a null in the array. Why does the array have null values?
Here is the code for setting the string array, the input is "DO UNTO OTHERS AS YOU WOULD HAVE THEM DO UNTO YOU":
String[] stringArray = new String[wordCount];
while (!line.equals("DONE"))
{
for ( int k = 0 ; k < wordCount ; k++)
{
//put tokens into string array
StringTokenizer tokens = new StringTokenizer(line);
stringArray[k] = tokens.nextToken();
}
}
Here is the code for the comparison and if statement that causes NullPointerException:
for ( int j = 0 ; j < wordCount ; j++)
{
for (int i = j+1 ; i < wordCount ; i++)
{
if (stringArray[i] == null)
{
stringArray[i] = "null";
}
else if (stringArray[i].compareTo(stringArray[j]) == 0 && i!=j)
{
//duplicate
System.out.print("\n" + stringArray[j]);
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: " + wordCount);
I am trying to null check but the result is still way off because it adds more to duplicates because when i change stringArray[i] to "null" it changes stringArray[j] also
please help! i've been trying to solve this for so long