我正在尝试在对象类中保存x个整数。我正在通过array进行尝试,但不确定是否可行,到目前为止,eclipse给了我两个错误。一个要求我在我的Gerbil()类中插入一个Assignment运算符,另一个要求我不能对非静态字段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();
    }

}
}
}

最佳答案

您需要在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();
}


}

或类似的事情应该做到这一点。

关于java - Java:在对象类内部创建数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23165611/

10-09 05:25