程序无法识别我输入了gerbil.foodTypes的值(gerbil.foodName.length的值为0。为什么?
class Gerbil {
public int foodTypes;
public String[] foodName = new String[foodTypes];
}
public class mainmethod {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
Gerbil gerbil = new Gerbil();
System.out.println("How many types of food do the gerbils eat?");
gerbil.foodTypes = keyboard.nextInt();
for (int x = 0; x < gerbil.foodTypes ; x++) {
System.out.println("Enter the name of food item " + (x+1));
gerbil.foodName[x] = keyboard.nextLine();
keyboard.nextLine();
System.out.println("Maximum consumed per gerbil:");
gerbil.foodMax[x] = keyboard.nextInt();
}
答案 0 :(得分:0)
public int foodTypes;
public String[] foodName = new String[foodTypes];
在评估foodTypes
时, new String[foodTypes]
为0,因此foodName
始终为零长度数组。
可能添加一个带foodTypes
的构造函数。
Gerbil gerbil = new Gerbil(keyboard.nextInt());
答案 1 :(得分:0)
构造类时,数组'foodName'的启动长度为零。这样做的原因是当你声明一个整数,例如。public int foodTypes'
时,所有编译器看到的都是public int foodTypes = 0;
初始化后无法调整数组的大小,因此无法“重置”数组的大小。
我会添加一个构造函数,它从输入中获取一个数字并将其分配给foodTypes,因此它不是0.
这是一些未经测试的代码:
class Gerbil {
public int foodTypes;
public String[] foodName;
public Gerbil(int num){
this.foodTypes = num;
this.foodName = new String[foodTypes];
}
}
public class Assignment4 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
Gerbil gerbil = new Gerbil(keyboard.nextInt());
for (int x = 0; x < gerbil.foodTypes ; x++) {
System.out.println("Enter the name of food item " + (x+1));
gerbil.foodName[x] = keyboard.nextLine();
keyboard.nextLine();
System.out.println("Maximum consumed per gerbil:");
gerbil.foodMax[x] = keyboard.nextInt();
}
Here是有关数组的更多文档。