This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Hello everyone, I'm studying Java with the Head First Java book and currently am at the I/O chapter, so one of the exercises is to make a Quiz Card class, builder and player.
However, I'm having issues with the builder as, for some reason, the program is not being able to read the content in the JTextAreas where you type your desired question and answer, whenever I try to do anything with the data, it throws a NullPointerException at runtime, even if the field is not blank and even after putting a setText() just before it.
If anyone could give me any insight of what is going wrong, I'd really appreciate it as I wasn't able to find any iffy code (I might be wrong) or a way to make it work, trying everything in my still limited knowledge to fix it, such as the aforementioned setText(), checking if the problem was the button, etc.
Here's the code as provided in the book (and from what I've learned so far, it was supposed to work):
It also uses a separate QuizCard class, which anyone using the book should write on their own and mine's as such:
I've considered the possibility of the problem being with my class, however testing everything by removing all instances where the separate class was called still gave me the exception, so it doesn't seem to be the problem (again, might be wrong).
You declare the "answer" variable at line 9 of your code, but you never assign anything to it. So it's always null. And then when you try to use it at line 75, you get a NullPointerException because it's null.
You may have thought that you assigned something to it at line 34. But you didn't. You declared a local variable of the same name, and assigned a reference to your JTextArea to that local variable instead of the instance variable declared at line 9.
Solution? Don't declare a local variable at line 34. Use the instance variable which is already available.
Joined: Mar 28, 2012
Whoa, thank you very much, it worked like a charm!
I didn't know/think that it meant declaring a new variable (and I did the same to the question variable).
Looking at it again, the book code doesn't declare them again, so it is most probably something I typed without properly realizing it and then proceeded to focus on the wrong part of the problem.
Anyway, again, I thank you very much for your help, Paul, I was already getting kinda desperate for not figuring what was wrong with the code.