This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have the following code that is supposed to take entries at different position and display them in a JTextArea. My problem is that whenever the method is executed, only the last entry I made is returned. Here is the code:
Why is only the last entry being displayed and what do I need to display all of them?
You don't want the new in the addEntry method, that's for sure. I'm a bit confused why you would be receiving the NPE whith that line in the constructor. Perhaps if you posted your whole code we would get a better idea of what is going on.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Joined: Dec 02, 2004
In the addEntry method I tried putting something as simple as output.setText(addressFile.fileStatus()) and it STILL gave me a nullpointerexception, even with that line in the constructor. I'm boggled as to what is making addressFile null when I'm defining it in the constructor!
As Michael says, the later (incorrect) version declares a NEW local variable with the same name. This variable "disappears" after the constructor completes. However, the member field is never changed and retains its default value, which is null, and thus causes the later NPE.
One way to help you avoid such errors is to use the "this" keyword when referring to member variables. To do this, you change the first (correct) code snippet above to this:
I typically like this syntax because it helps me to distinguish between member fields and local variables.