我的代码有问题。
首先,这是我的代码。
public class Zoo {
public int j=0;
public Animal[] park;
// Exercise 9
public Zoo() {
Animal[] park = new Animal[10];
}
// Exercise 10
public void addAnimal(Animal first) {
for (int i = 0; i < 10; i++) {
if (park[i] != null) {
park[i] = first;
i=j;
i = 10;
} else if (i == 9) {
System.out.println("The zoo is full!");
}
}
}
// Exercise 11
public void feed() {
for (int i = 0; i < 10; i++) {
park[i].mass *= 1.1;
}
}
public String toString() {
String result = "The list:\n";
for (int i = 0; i< 10; i++) {
result = result + "cage " + i + " status:" + park[i] + "\n";
}
return result;
}
public void print() {
System.out.println(park.toString());
}
public int totalLegs() {
int totalLeg = 0;
for (int i = 0; i < 10; i++) {
totalLeg += park[i].legs;
}
return totalLeg;
}
}
还
public class Animal {
float mass;
String name;
int legs;
// Exercise 6-6
public Animal(String randomName) {
name = randomName;
legs = 0;
mass = 0;
}
// Exercise 6-7
public Animal(float one, String two, int three) {
mass = one;
name = two;
legs = three;
}
//Exercise 7
public String toString(){
return "name =" + name + "legs=" + legs + "mass=" + mass;
}
public void massSetter() {
}
public String getName() {
return name;
}
public int getLegs() {
return legs;
}
}
和
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
Animal elephant = new Animal(300f,"elephant",4);
Animal spider = new Animal(0.5f,"spider",6);
Animal snake = new Animal(10f,"snake",0);
zoo.addAnimal(elephant);
zoo.addAnimal(spider);
zoo.addAnimal(snake);
zoo.print();
System.out.println("Average number of legs is");
}
}
您可能从代码中可以看出,我对编程非常陌生,当我运行最后一个类(TestZoo.java)时,它给了我以下错误。
Exception in thread "main" java.lang.NullPointerException
at Zoo.addAnimal(Zoo.java:13)
at TestZoo.main(TestZoo.java:9)
我做了一些搜索,显然当我尝试传递一个空值时,我得到了这个错误,就好像它有什么东西一样。
我查看了 Zoo 类的第 13 行,老实说,我不知道如何解决这个问题。
任何帮助将不胜感激。
提前致谢