在Java中将对象添加到空数组中

时间:2013-08-03 23:49:29

标签: java arrays class null nullpointerexception

我一直在为班级继承做练习。抽象类。我对这两个概念非常有信心,但正如标题所示,我(仍然)在将对象添加到类型类数组时遇到了麻烦。

问题如下:有三种主要类型的文件,

  1. 类Zoo文件(包含main方法)
  2. 抽象类动物文件
  3. 和任何数量的特定动物(牛,马,等等)是派生类, 你猜对了,类动物。
  4. Class Zoo

    public class Zoo 
    {
    
    private int actual_num_animals;
    private int num_cages;
    private Animal[] animals;
    
    
    Zoo()
    {
        actual_num_animals = 0;
        num_cages = 20;
    }
    
    Zoo(int num_cages)
    {
        this.num_cages = num_cages;
    }
    
    // adds an animal to Zoo
    public void add(Animal a)
    {
        for(int i = 0; i < num_cages; i++)
        {
            if(animals[i] != null && animals[i].equals(a) == true)
            {
                System.out.println(a.getName() + " is already in a cage!");
                break;
            }
            else if(animals[i] == null)
            {
                animals[i] = a;
                actual_num_animals++;
                break;
            }
        }
    
    }
    
    
    
    // returns the total weight of all animals in zoo
    public double total_weight()
    {
        double sum = 0;
    
        for(int i = 0; i < actual_num_animals; i++)
        {
            sum += animals[i].getWeight();
        }
        return sum;
    }
    
    //Print out the noises made by all of the animals.
    //In otherwords, it calls the makeNoise() method 
    //for all animals in the zoo.
    public void make_all_noises()
    {
        for(int i = 0; i < actual_num_animals; i++)
        {
            animals[i].makeNoise();
            System.out.print("! ");
        }
    }
    
    //prints the results of calling toString() on all animals in the zoo.
    public void print_all_animals()
    {
        for(int i = 0; i < actual_num_animals; i++)
        {
            animals[i].toString();
            System.out.print(" ");
        }
    }
    
     public static void main(String[] args)
        {
            Zoo z = new Zoo();
            Snake sly = new Snake("Sly", 5.0 , 2, 2);
            Snake sly2 = new Snake("Slyme", 10.0 , 1, 2);
            Cow blossy = new Cow("Blossy", 900., 5,  10);
            Horse prince = new Horse("Prince", 1000., 5, 23.2);
    
            // Following not allowed because Animal is abstract
            //Animal spot = new Animal("Spot", 10., 4);
    
            z.add(sly);
            z.add(sly2);
            z.add(blossy);
            z.add(prince);
    
            z.make_all_noises();
            System.out.println("Total weight =" + z.total_weight());
            System.out.println("**************************");
            System.out.println("Animal Printout:");
            z.print_all_animals();  
    
        }
    }
    

    我的问题在于此处的add方法。我在第一个if语句

    中不断获得空指针异常
    if(animals[i] != null && animals[i].equals(a) == true)
    

    以及第一次在main方法中调用此add方法。显然, 这种情况有问题,可能是伴随它的其他条件。

    对于我的生活,我无法理解,它不起作用。更糟糕的是,我在之前的练习中遇到了类似的问题:

    Class Inheritance in Java

    为类Zoo编写的if和else-if条件遵循上一个问题中概述的add函数中完全相同的格式,这是最令人费解的一点。 你们有什么想法吗?

    最后,作为参考,虽然我怀疑你是否需要它,但我将在下面包含动物类文件和派生类奶牛文件:

    抽象类动物

    public abstract class Animal
    {
    private String name;
    private double weight;
    private int age;
    
    Animal()
    {
        name = "noName";
        weight = 0;
        age = 0;
    }
    
    Animal(String n, double weight, int age)
    {
        name = n;
        this.weight = weight;
        this.age = age;
    }
    
    abstract String makeNoise();
    
    String getName()
    {
        return name;
    }
    
    double getWeight()
    {
        return weight;
    }
    
    int getAge()
    {
        return age;
    }
    
    public String toString()
    {
        return name + ", weight: " + weight + "age: " + age;
    }
    
    }
    

    派生类Cow

    public class Cow extends Animal 
    {
    private int num_spots;
    
    Cow()
    {
        super();
        num_spots = 0;
    }
    Cow(String name, double weight, int age, int num_spots)
    {
        super(name, weight, age);
        this.num_spots = num_spots;
    }
    
    String makeNoise() 
    {
        return "Moooo";
    }
    
    public String toString()
    {
        return getName() + ", weight: " + getWeight() + "age: " + getAge() +
                "num spots: " + num_spots;
    }
    }
    

2 个答案:

答案 0 :(得分:2)

在Zoo构造函数中添加一行以初始化数组:

Zoo()
{
    actual_num_animals = 0;
    num_cages = 20;
    animals = new Animal[num_cages];
}

你可能也希望实现equals()"Bloch way"是一个很好的实现)。

答案 1 :(得分:0)

在我看来,你永远不会初始化

private Animal[] animals;

你应该做

animals = new Animal[tot];

其中tot是您要放入的动物总数。请注意,您可能需要ArrayList而不是数组,例如,以避免给出起始维度。