[Logo]
Forums Register Login
Null pointer Exception
As usual, there is probably something most obvious I'm missing, but I cant understand why the following code is throwing a nullPointerException. I ssume it has something to do with the initialization of my Array of feeling objects in the Game Constructor?

Firstly here is my Feeling class:





Following is the Game class which is throwing the null pointer exception:




Ant suggestions?
The feelings array you declare and initialize at line 3 of the second code sample does not contain any references to actual Feeling objects yet.
It's basically an array of null references at that point. When at line 9 you start looping over the feelings array and attempt to access the Feeling object refered to at array index 0, there's no actual object there, so as soon as you call the setFeeling() method a NullPointerException will be thrown.
You can solve this by creating a new Feeling object inside the loop, using the default constructor, then calling the setter methods on that object reference and finally shoving the reference into the array at the appropriate index. Alternatively, you could define a constructor for the Feeling class that takes both parameters, so you needn't call the setter methods after object creation.
Doh! of course, thanks Jelle. infact in an older version I was working on I had a line similar to that. It now works like a charm. Its always the most obvious things I miss! ops:
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss


This thread has been viewed 729 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 20, 2018 22:14:46.