Reputation: 557
I'm having a problem with adding objects to an arrayList in Java. I'm getting the following error when I run my code. This is a snippet of two of my files. I'd be much obliged were anyone to point out my error. Thanks, Joe
java.lang.NullPointerException at House.addRoom(House.java:18)at House.(House.java:36)
//ROOM CLASS
public Room () {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter description of room:");
description = scan.next();
System.out.println("Enter length of room:");
length = scan.nextDouble();
System.out.println("Enter width of room:");
width = scan.nextDouble();
}
//HOUSE CLASS
public class House {
private static ArrayList<Room> abode;
public void addRoom (){
abode.add(new Room ());
}
public House () {
idNum = ++internalCount;
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter address of house:");
address = scan.next();
System.out.println("Enter number of rooms:");
numRooms = scan.nextInt();
System.out.println("Enter type of house:");
houseType = scan.next();
for (int i=1; i<=numRooms; i++){
addRoom();
}
}
}
Upvotes: 0
Views: 2424
Reputation: 135
Joe, First you need to create object before accessing any object's fields or methods.
In your code, private static ArrayList abode; // Object has not been created
you are declaring only reference which is by default pointing to null. Basically, You are not allocating any memory in heap to store object's state. So, first you need to create an object of ArrayList class using new operator and after that you can perform various actions on this object. so, replace your code to
private static ArrayList abode = new ArrayList();
Upvotes: 0
Reputation: 142
joe u can add the array list using List
for eg. ArrayList results = new ArrayList();
List< ResolveInfo>
and then
results.add();
Upvotes: 0
Reputation: 839
Change this
private static ArrayList<Room> abode;
to
private static ArrayList<Room> abode = new ArrayList<Room>();
You are trying to use the list reference without allocating memory for it.
Upvotes: 0
Reputation: 500177
You need to create a list:
private static ArrayList<Room> abode = new ArrayList<Room>();
If you don't, abode
will be null
and you'll get a NullPointerException
.
Also, is there a reason abode
is static
? This means that it's shared by all instances of House
. Is that what you're intending?
Upvotes: 1
Reputation: 46398
you need to initialize your arraylist
before you add elements in it.possibly initialize in your constructor
private static ArrayList<Room> abode;
public House()
{
abode = new ArrayList<String>();
//rest of your code
}
Btw, its always a good practice to code to an interface than to an implementation:
i.e., List<Room> abode = new ArrayList<String>();
Upvotes: 3