用对象填充空数组

时间:2019-12-07 21:56:03

标签: java arrays

我正在创建一个N个空格(由用户定义)的狗窝,我需要用N个空对象填充空数组,以便以后查看。

这是创建狗窝数组的类,注意:我尝试使用对象的ArrayList <>,但无法从中获取所需的信息。


public class Kennel {

    private Object[] kennel;
    private String type;
    private int space;
    public Kennel() {

    }
    public Kennel(String type, int space) {
        //initialize Kennel with type of animal and number of kennel spaces available.
        this.type = type;
        this.space = space;
        kennel = new Object[this.space];

    }
    //populate the kennel
    public void populateKennel() {
        for (int i = 0; i < this.kennel.length; ++i) {
                     //Has a constructor that sets a certain number of values in the object to empty.
            RescueAnimal animal = new RescueAnimal();
            //my attempt to add the object to the kennel
                        kennel[animal];
        }
        System.out.println(kennel);
    }

}

这是RescueAnimal类中的toString(),这是应该添加到数组中的数据,所有数据均带有“ none”或“ empty”值,以后应以这种方式打印出来。

    public String toString() {
       // return name; type; gender; age; weight; acquisitionDate; statusDate; acquisitionSource;
        return( "Name: " + this.name + " Type: " + this.type + "\n"
              +"Gender: " + this.gender + " age: " + this.age + "\n"
              +"Weight: " + this.weight + " Day acquired: " + this.acquisitionDate + "\n"
              +"Status: " + this.statusDate + " Acquired: " + this.acquisitionSource + "\n\n");
    }

在代码的主要部分中,我尝试使用动物(Dog)类型和狗窝空间(10)的数量调用New kennel数组,并尝试用空对象填充该狗窝。

Kennel dogKennel = new Kennel("Dog", 10);
dogKennel.populateKennel();

无论如何,我的尝试都未能成功完成,但我仍然在Kennel类中返回初始化错误。

你们有什么指针可以帮助我完成这项任务吗?

2 个答案:

答案 0 :(得分:0)

使用以下命令设置数组的成员

kennel[i] = animal;

答案 1 :(得分:0)

为什么不将狗窝对象设置为救援动物数组: `

公共类狗窝{

private RescueAnimal[] kennel;
private String type;
private int space;

public Kennel(String type, int space) {
    //initialize Kennel with type of animal and number of kennel spaces available.
    this.type = type;
    this.space = space;
    kennel = new RescueAnimal[this.space];

}
//populate the kennel
public void populateKennel() { // would rename this to initializeKennel since the data inside is empty
    for (int i = 0; i < this.kennel.length; ++i) {
        //Has a constructor that sets a certain number of values in the object to empty.
        RescueAnimal animal = new RescueAnimal();

        kennel[i]= animal;
    }
    //System.out.println(kennel);
    //remove this, only want to print after there is data in it and you have defined a toString for Kennel
}
public String toString(){
    String s="Kennel Type: "+type + "Kennel Capacity: "+space + "animals: \n";
    for (int i =0; i < kennel.length; ++i){
        s+= kennel[i].toString()+"\n";
    }
    return s;
}

}

`

相关问题