有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

  1. # 1 楼答案

    您需要通过沙鼠构造器中的食物数量:

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

    }

    或者类似的东西就可以了