Hi i get a null pointer where marked in the process. The tester class is at the bottom. It happens when trying to printout the zoo.
It seems to be the no name is set for “Animal animal” but I have created animals.
It could be accessing the wrong animal i want, but then how do I access the animals in the list I’ve made (please no using the “:” in the for parameter)!
i know this is wrong but something like animal_list.printdetails?
public class Zoo {
private Animal animal;
public int number_animals;//# animals allowed in zoo
private List<Animal> animal_list;
private String zoo_name;
public Zoo(String name){
this.zoo_name = name;
animal_list = new ArrayList<Animal>();
}
public void addAnimal(Animal obj) {
animal_list.add(obj);
}
public String toString(){
String s = "In zoo " + zoo_name + " there are the following animals:\n";
for (int i = 0; i < animal_list.size(); i++){
s += animal.getName() + " who weighs " + animal.getWeight() + " kg.";//null pointer on this line why??? i have made an animal. How do I access this animals in the list (please no using the ":" in the for parameter)!
}
return s;
}
public class Animal {
public String name;
public int weight;
private String food_type;
private int space_requirement;
private Zoo zoo;
private Animal animal;
public Animal(String name, int weight){
this.name = name;
this.weight = weight;
}
public String getName(){
return this.name;
}
public int getWeight(){
return this.weight;
}
public class Test {
public static void main(String[] args) {
Zoo diego = new Zoo("San Diego");
Animal giffy = new Animal("Giffy", 950);
Animal gunther = new Animal("Gunther", 950);
diego.addAnimal(giffy);
diego.addAnimal(gunther);
System.out.println(diego);
}
Because you aren’t using your
List, you’re trying to reference theanimalfield in yourZoo(which you don’t actually use anywhere). You have to get yourAnimals from youranimal_listNote also that you really should be using a
StringBuilderhere rather than creating newStringobjects with the+=and+operators:Strings are immutable in Java; you can’t alter them. When you concatenate them using+=or+you’re actually creating newStringobjects and discarding the old ones. The compiler will actually optimize this away where it can to aStringBuilder, but good practice is not to leave it to the compiler.Edit to add:
In case you’re not familiar, the above is an example of method chaining
When you say something like:
It’s the equivalent of: