public boolean addPrisoner(Prisoner p)
{
if(population < capacity) //checks to make sure there is room in the prison
{
prisoners.add(p); //prisoners is the ArrayList containing all prisoners
population++; //population is increased when prisoner is added
return true;
}
else
return false;
}
NullPointerException in java
For Comp Sci class I am creating a prison simulation since we are learning about searches and sorts. I have 3 classes in this project, a Prisoner class, a Prison class, and a driver class with a main method to run the prison. The Prisoner class defines a prisoner, and the Prison class is essentially an ArrayList of prisoners with methods to add, remove, sort, and search through the prisoners. My problem is I keep getting a NullPointerException when I try to add a Prisoner object to the ArrayList in the Prison class.
In my Prison class I have the following method:
In the driver program I create a new Prison object, then create a Prisoner object. When I call the addPrisoner method to add the Prisoner to the Prison, I get a NullPointerException and I am not sure why. I'd like to figure out why I am getting this exception so that then I can fix it.
Try adding some logging statements (System.Out.Println()) to check that prisoners isn't null. Either it or p is null. You have actually allocated prisoners with new, haven't you?
And does ArrayList not have a size() or count() member (It's been ages since I used Java)? That'd mean you can get rid of population.
And does ArrayList not have a size() or count() member (It's been ages since I used Java)? That'd mean you can get rid of population.
How hard is this?
Toolmaker
public class Prison{ private ArrayList prisoners = new ArrayList(); private int capacity = 0; public Prison(int c) { capacity = c; } public boolean addPrisoner(Prisoner p) { if(prisoners.size() < capacity) //checks to make sure there is room in the prison { prisoners.add(p); //prisoners is the ArrayList containing all prisoners return true; } else return false; }}
Toolmaker
In Java, variables of object type are effectively pointers, and they get default-initialized to null whenever they actually are default-initialized. Therefore if you declare a class member ArrayList like this:
Then it is equivalent to
and not to Toolmaker's version.
private ArrayList prisoners;
Then it is equivalent to
private ArrayList prisoners = null;
and not to Toolmaker's version.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement