-1

The program will not recognize that I have entered a value for gerbil.foodTypes (giving me a value of 0 for gerbil.foodName.length. Why?

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

2 Answers2

0
public int foodTypes;
public String[] foodName = new String[foodTypes];

foodTypes is 0 when new String[foodTypes] is evaluated so foodName is always a zero length array.

Maybe add a constructor that takes foodTypes.

Gerbil gerbil = new Gerbil(keyboard.nextInt());
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

When you construct your class, your array 'foodName' is initiated with a length of zero. The reason for this is that when you declare an integer eg.public int foodTypes', all the compiler sees is public int foodTypes = 0;

Arrays cannot be resized after you have initialized them so you cannot 'reset' the size of the array.

I would add a constructor that takes a number from input and assigns that to foodTypes so it is not 0.

here is some untested code:

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 is some further documentation on arrays.

Matt Hirdler
  • 95
  • 1
  • 10