因此,我已经阅读了关于stackoverflow的所有构造函数未定义的文章,并尝试了解决方案,但它们对我没有用。也许我尝试错了。我不断收到“构造函数Gerbil(int)未定义”。

问题所在的代码:

GerbilArray[i] = new Gerbil(i);


我的完整代码:

import java.util.Scanner;
public class Gerbil {

public String name;
public String id;
public String bite;
public String escape;

public Gerbil() {
    this.name = "";
    this.id = "";
    this.bite = "";
    this.escape = "";
}

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("How many foods?");
    int totalFood = keyboard.nextInt();

    System.out.println("How many gerbils in the lab?");

    int numberOfGerbils = keyboard.nextInt();
    Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];

    for(int i = 0; i <= numberOfGerbils; i++){
        GerbilArray[i] = new Gerbil(i);

        System.out.print("Lab ID:");
        String id = keyboard.next();

        System.out.print("Gerbil Nickname:");
        String name = keyboard.next();

        System.out.print("Bite?");
        String bite = keyboard.next();

        System.out.print("Escapes?");
        String city = keyboard.nextLine();

        for (int j = 0; j < totalFood; j++) {
            System.out.println("How many of food " + (j+1) + "do you eat?:");

        }

    }
}
}


您还可能已经看到我的嵌套for循环还没有完成。我试图在一个对象内部创建一个数组,该数组将在用户列出的对象内部存储“ x”个整数(int totalFood),但是我不知道如何。

最佳答案

您在类Gerbil(int a)中没有构造函数Gerbil,然后尝试调用它!

只是这样称呼它:

GerbilArray[i] = new Gerbil();

10-08 00:27