I have an array of Strings called letters. When I try to execute the following line of code, I get a NullPointerException.
if(letters[j].equals(tmpst))
Where j is an arbitrary index less than the length of letters
tmpst is a string that is defined as such:
char myChar = theWord.charAt(i);
String tmpst = String.valueOf(myChar);
where theWord is an arbitrary string with length greater than 4.
The full code is:
for (int i = 0; i < theWord.length(); i++) {
for (int j = 0; j < letters.length; j++) {
char myChar = theWord.charAt(i);
String tmpst = String.valueOf(myChar);
if(letters[j].equals(tmpst)) {
System.out.println("YOU DIDIT!!! :D");
newWord = newWord + theWord.charAt(i);
}
}
Can someone see what I’m doing wrong?
Thanks.
It seems that your array contains some null references. You can use
Arrays.toString(letters)to see if it is true.If you want that your comparisson still works even if your array contains null values, you should change your code to be like this: