【问题标题】:class won't recognize user input? [duplicate]类不会识别用户输入? [复制]
【发布时间】:2014-04-08 04:11:55
【问题描述】:
程序将无法识别我输入了 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();
}
【问题讨论】:
标签:
java
arrays
class
input
user-input
【解决方案1】:
public int foodTypes;
public String[] foodName = new String[foodTypes];
foodTypes 在计算 new String[foodTypes] 时为 0,因此 foodName 始终是零长度数组。
也许添加一个采用foodTypes 的构造函数。
Gerbil gerbil = new Gerbil(keyboard.nextInt());
【解决方案2】:
当你构建你的类时,你的数组“foodName”的长度为零。原因是当你声明一个整数 eg.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 是有关数组的更多文档。