• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why am I getting this Null Pointer Exception?  RSS feed

 
Mikelo Vatki
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was trying to model a board game called "Risk" in Java when I came upon this persistent error. I can't seem to figure out why java is throwing a null pointer exception. I have three classes, risk.class, territory.class and terrHandler.class but I have removed some of the excess code that is not related to this problem. Below is the code.

risk


territory



terrHandler


"territories[q].setConnection(r);" is what is causing the exception but I don't understand what could be null here. Thanks in advance to anyone who responds.

Mikelo Vatki
 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

How many elements did you assign (if any) to the isConnectedTo array? It is never initialized... this will throw a NullPointerException unless you initialize your array.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More specifically,

new territory[numOfTerritories];

doesn't instantiate any territory objects. All it does is instantiating an array of references to territory objects. All those references will initially be set to null.

As an aside, general coding convention is to have class names start with a capital letter. Not doing so will make it much harder for others to read your code.
 
Mikelo Vatki
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright, I found my mistake. Thanks to both of you for responding. I simply added a while loop to properly initialize each element in each of the arrays. I added a function to cycle through isConnectedTo[] and set each element to false. I have renamed all of my classes so that they conform to the convention as well (Ilja Preuss, thank you for pointing that out).
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mikelo Vatki:
I added a function to cycle through isConnectedTo[] and set each element to false.


Oh, *that*'s redundant. All array elements are automatically initialized to their default value - for object references, that's null, for booleans false (for numerical primitives zero).
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would you consider for loops in your code?

The way you've written your loop:



The way you could consider a loop like that:



 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!