My code is this:
public class Main{
public static void main(String[] args){
WordGroup wordgroupOne= new WordGroup ("You can discover more about a person in an hour of play than in a year of conversation");
WordGroup wordgroupTwo= new WordGroup ( "When you play play hard when you work dont play at all");
String[] quoteOne = wordgroupOne.getWordArray();
String[] quoteTwo = wordgroupTwo.getWordArray();
for (String word : quoteOne){
System.out.println(word);
}
for (String word : quoteTwo){
System.out.println(word);
}
}
}
Wordgroup class:
public class WordGroup {
public String words;
public WordGroup (String getWords){
words = words.toLowerCase();
}
public String[] getWordArray(){
return words.split(" ");
}
}
It compiles fine but when I try to run it I get the error java.lang.NullPointerException
and it highlights "words = words.toLowerCase();
" (I'm using blueJ) what is causing this?
When researching it says that this error is when you try to operate on a null set but the WordGroup
is not null as it has a string defined in Main.
Because the default value (see default value section) for every object is null
. Since you didn't initialize words
, the NPE is thrown.
public WordGroup (String getWords){
words = words.toLowerCase(); <- here words is null so a NPE is thrown
}
But I think you didn't correctly set up your constructor; it should be :
public WordGroup (String getWords){
words = getWords.toLowerCase();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With