I had to write a program that created a pantry which was an array of three jams. When I tried to print out my array, I got a nullpointerexception. What is a nullpointer exception? How can they be fixed?
Thank you for your help!!!
Joined: Feb 23, 2009
first, please always post the exact exception so it's easier to find the piece of code that causes trouble.
I went through it real quick and think that I found the spot.
What you do is create a Jam array as a local variable but don't put any values in it. Hence the value of each index is null which means it has not gotten a reference yet.
Upon invoking a method on a variable that is null, you'll get a big fat nullpointer exception.
What you want to do is make your Jam array an instance variable and pass the values in the constructor.
JDBCSupport - An easy to use, light-weight JDBC framework -
Joined: Dec 22, 2009
Sebastian's answer looks like the problem, to me, too. Also, I noticed you're assigning things to the 'patry1' local variable in the Pantry constructor. Since you don't do anything with them, I assume that you probably meant them to persist, in which case you would want to assign them to a member variable. Something like:
(the foreach loop iterates over every item in the array. You probably do not want "for (int i = 0; i < 3; i++)" since if you ever change the length of the array your code will break. "for (int i = 0; i < items.length; ++i)" is better, but the foreach loop is more concise.)
The NullPointerException name is a bit confusing, because what most CS people call "pointers", Java usually calls "references". Basically if you try to do anything will a null reference besides checking to see if it's null, you'll get a NullPointerException. Look at the output window and you'll see a stack trace that points you to the exact line that causes the problem.