Qua*_*245 1 java methods class list nullpointerexception
嗨我得到一个空指针在过程中标记.测试者类位于底部.当试图打印动物园时会发生这种情况.似乎没有为"动物动物"设置名称,但我创造了动物.
它可以访问我想要的错误动物,但是我如何访问我已经制作的列表中的动物(请不要使用for参数中的":")!我知道这是错的,但像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);
}
Run Code Online (Sandbox Code Playgroud)
for (int i = 0; i < animal_list.size(); i++){
s += animal.getName() + " who weighs " + animal.getWeight() + " kg.";
}
Run Code Online (Sandbox Code Playgroud)
因为你没有使用你的List
,所以你试图引用你的animal
字段Zoo
(你实际上并没有在任何地方使用它).你必须得到你Animal
的animal_list
for (int i = 0; i < animal_list.size(); i++){
s += animal_list.get(i).getName() + " who weighs " +
animal_list.get(i).getWeight() + " kg.";
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您确实应该使用StringBuilder
此处而不是String
使用+=
和+
运算符创建新对象:
public String toString() {
StringBuilder s = new StringBuilder("In zoo ");
s.append(zoo_name).append(" there are the following animals:\n");
for (int i = 0; i < animal_list.size(); i++){
s.append(animal_list.get(i).getName());
s.append(" who weighs ");
s.append(animal_list.get(i).getWeight());
s.append(" kg.\n");
}
return s.toString();
}
Run Code Online (Sandbox Code Playgroud)
String
s在Java中是不可变的; 你无法改变它们.当您使用它们连接它们+=
或者+
实际上是在创建新String
对象并丢弃旧对象时.编译器实际上会将它优化到最佳位置StringBuilder
,但是好的做法是不要将它留给编译器.
编辑添加: 如果您不熟悉,以上是方法链接的示例
当你说的话:
String name = animal_list.get(i).getName();
Run Code Online (Sandbox Code Playgroud)
它相当于:
Animal a = animal_list.get(i);
String name = a.getName();
Run Code Online (Sandbox Code Playgroud)