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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18038419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:58:40  来源:igfitidea点击:

adding objects to an empty array in Java

javaarraysclassnullnullpointerexception

提问by HelloMyNameIsRay

I've been doing an exercise for class inheritance & abstract classes. I feel pretty confident with those two concepts, but as the title suggests, I'm (still) having trouble with adding objects to an array of type class.

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

The problem is as follows: there are 3 main types of files,

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

  1. a class Zoo file (contains main method)
  2. an abstract class animal file
  3. and any number of specific animals (cow, horse, whatever) which are derived classes of, you guessed it, class animal.
  1. 一个类 Zoo 文件(包含 main 方法)
  2. 抽象类动物文件
  3. 以及任意数量的特定动物(牛、马等),它们是您猜对了类动物的派生类。

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();  

    }
}

My problem resides within the add method here. I am continually getting a null pointer exception at the first if statement

我的问题存在于这里的 add 方法中。我在第一个 if 语句中不断收到空指针异常

if(animals[i] != null && animals[i].equals(a) == true)

as well as the first time this add method is being called within the main method. Clearly, there is something wrong with this condition, and likely the else-if condition that accompanies it.

以及第一次在 main 方法中调用此 add 方法。很明显,这个条件有问题,很可能是伴随它的 else-if 条件。

For the life of me I can't understand, it's not working. What's worse is that I encountered a similar problem on a previous exercise here:

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

Class Inheritance in Java

Java中的类继承

The if and else-if condition written for class Zoo follows the exact same format in the add function outlined in this previous question, which is the most puzzling point of all. Any ideas you guys?

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

Lastly, for reference, though I doubt you'll need it, I'll include the animal class file and a derived class cow file below:

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

Abstract Class Animal

抽象类动物

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;
}

}

Derived class 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;
}
}

采纳答案by earcam

Add a line to your Zoo constructor to initialize the array:

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

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

You probably want to implement equals()as well (the "Bloch way"is a good implementation).

您可能还想实现equals()“Bloch 方式”是一个很好的实现)。

回答by Alberto Zaccagni

It seems to me that you never initialize

在我看来你从不初始化

private Animal[] animals;

you should do

你应该做

animals = new Animal[tot];

where totis the number of total animals you are going to put in there. Note that you might want an ArrayListinstead of an array, for example to avoid giving a starting dimension.

这里tot是总的动物的数量你要摆在那里。请注意,您可能需要一个ArrayList而不是数组,例如为了避免给出起始维度。