【问题标题】:Java: creating an array inside of an object class?Java:在对象类中创建一个数组?
【发布时间】:2014-06-03 15:23:44
【问题描述】:

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

}
}
}

【问题讨论】:

  • food[j] = keyboard.nextInt();。这是谁的菜?
  • food[j] 是 gerbilArray[i] 的食物。我希望它运行 j = 食物总数。但我希望它能够保存每种特定的食物,并为每只沙鼠做到这一点。所以 gerbilArray[i+1] 会被问同样的问题,并且可以为每种食物 food[j] 保存不同的数字。
  • 这是因为 i
  • 您找到了答案,并不意味着您应该清除问题并告诉我们必须删除它。

标签: java arrays object for-loop


【解决方案1】:

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

}

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

【讨论】:

  • 那你应该投票给我的答案。这是本网站的全部概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
  • 2011-07-18
相关资源
最近更新 更多