Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Null pointer Exception

 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic