迭代和显示多个数组的问题

时间:2018-04-28 16:55:05

标签: java arrays methods

我创建了这个方法buildDogs(),它创建了5个bean并将它们存储到一个数组中。然后我创建了一个方法displayDogs(),它应该遍历5,并使用toString输出它们。最后,在我的main方法中,我需要将displayDogs()方法存储到名为allDogs的数组中。但是,每当我尝试在buildDogs()方法中调用main时,我只会收到一条错误,指出我无法在static void main中使用非静态方法。我不知道我搞砸了哪里,你看到我做错了吗?这是我的作业的确切课程,以及到目前为止我的代码。

课程
buildDogs”
这种非静态方法没有参数 它使用硬编码(程序员确定)值构建五个DogBeans。不要从命令行获取这些值!
把五个DogBeans放在一个数组中 返回DogBeans数组
“displayDogs”
这种非静态方法有一个参数 - 一个DogBeans数组 它遍历传递的数组,并为每个DogBean调用自定义的toString方法 “主”
这是标准的静态主要方法 在此方法中,您必须调用buildDogs并将结果存储在名为“allDogs”和
的DogBeans数组中 调用displayDogs并传递allDogs数组引用

Java代码:

public class Kennel {
public DogBean[] buildDogs(){
    DogBean dog1 = new DogBean(1, "blue", 1, "schnoodle", "clyde");
    DogBean dog2 = new DogBean(2, "yellow", 2, "dachsund", "jack");
    DogBean dog3 = new DogBean(3, "green", 3, "schnauzer", "john");
    DogBean dog4 = new DogBean(4, "red", 4, "poodle", "bonnie");
    DogBean dog5 = new DogBean(5, "purple", 5, "pitbull", "jacob");
    DogBean[] dogs = {dog1, dog2, dog3, dog4, dog5};
    return dogs;
}
public DogBean[] displayDogs(){

    DogBean[] dogsArray = buildDogs();
    /*for each loop*/
    for (int i = 0; i < dogsArray.length; i++)
        dogsArray[i].toString();
    System.out.printf(dogsArray + ", ");
return dogsArray;
}

public static void main(String[] arg) {
        DogBean[] allDogs = buildDogs();
        DogBean[] displayDogs = allDogs;
    }
}

1 个答案:

答案 0 :(得分:0)

buildDogsKennel实例的方法 - 根据您的代码。因此,您需要创建一个实例来访问它。

所以你应该以这种方式访问​​它:

public static void main(String[] arg) {
    DogBean[] allDogs = new Kennel().buildDogs();
    DogBean[] displayDogs = allDogs;
}

<强>更新

根据您在评论中的问题,这是displayDogs的正确实现。

public static void main(String[] arg) {
    DogBean[] allDogs = new Kennel().buildDogs();
    displayDogs(allDogs);
}

public static void displayDogs(DogBean[] allDogs) {
    for(DogBean dogBean : allDogs) {
        System.out.println(dogBean); // TODO: make sure you implement the toString() method of DogBean.
    }
}

更新2:

如果displayDogs不能是静态的,请将其设为实例方法:

public static void main(String[] arg) {
    final Kennel kennel = new Kennel();
    DogBean[] allDogs = kennel.buildDogs();
    kennel.displayDogs(allDogs);
}

public void displayDogs(DogBean[] allDogs) {
    for(DogBean dogBean : allDogs) {
        System.out.println(dogBean); // TODO: make sure you implement the toString() method of DogBean.
    }
}