Java:在对象类中创建一个数组?

时间:2014-04-19 03:55:08

标签: java arrays object for-loop

我试图在对象类中保存x个整数。我是通过array尝试的,但我不确定这是否可行,截至目前eclipse正在给我两个错误。一个要求我在我的Gerbil()课程中插入一个Assignment操作符,另一个要求我对{+ 1}}非静态字段static进行food引用。我要找的结果是food 1 = first input; food 2 = second input;,直到它达到食物的总量。

到目前为止,这是我的代码:

import java.util.Scanner;
public class Gerbil {

public String name;
public String id;
public String bite;
public String escape;
public int[] food;

public Gerbil() {
  this.name = "";
  this.id = "";
  this.bite = "";
  this.escape = "";
  this.food[]; // I'm not sure what I should put here. This is where I want to store
}              // the different integers I get from the for loop based on the
               // total number of foods entered. So if totalFoods is 3, there should
               // be 3 integers saved inside of the object class based on what's typed
               // inside of the for-loop. Or if totalFoods = 5, then 5 integers.

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();

    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?:");
        food[j] = keyboard.nextInt();
    }

}
}
}

1 个答案:

答案 0 :(得分:2)

您需要传递Gerbil构造函数中的食物数量:

public Gerbil(int totalFood) {
   this.name = "";
   this.id = "";
   this.bite = "";
   this.escape = "";
   this.food[] = new int[totalFood]; 
}

然后在循环中看起来像这样:

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

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?:");
    GerbilArray[i].food[j] = keyboard.nextInt();
}

}

或类似的东西应该这样做。