简体   繁体   中英

Trouble with Looping through Arrays

I am currently working on a homework assignment and was moving along quite nicely until I reached step 4 on my sheet. I don't understand how to make my code run through while moving to the next element in the array. We are using Eclipse IDE for Java Developers. Here is the assignment so that you can see what I am working on (Please don't help me with more than my question). (Whoops seems I can't post images. Will try to raise my reputation)

ALL COMMENTS AND SUGGESTIONS WELCOME BUT PLEASE DON'T HELP PAST STEP 4!

https://s29.postimg.org/p0n1lnemv/Screen_Shot_2014_04_15_at_10_24_49_AM.png http://s29.postimg.org/cok585qs7/Screen_Shot_2014_04_15_at_10_25_12_AM.png

Here is my code so far (I know the array class is not allowed but I use it to check my arrays):

import java.util.Scanner;
import java.util.Arrays;

public class ArrayPractice {

public static void main(String []args)

{
    System.out.println("How many food items do the gerbils eat?");
    Scanner keyboard = new Scanner(System.in);

    String diffFoods = keyboard.nextLine();
    int foodNum = Integer.parseInt(diffFoods);
    String foodNames[] = new String[foodNum];
    int foodMax[] = new int[foodNum];
    int j = 1;

    for (int i = 0; i < foodNum; i++)
    {
        System.out.println("Name of food item " +j +":");
        foodNames[i] = keyboard.nextLine();
        System.out.println("Maximum consumed per gerbil:");
        String maxCons = keyboard.nextLine();
        foodMax[i] = Integer.parseInt(maxCons);
        j++;
    }

    System.out.println("How many gerbils are in the lab?");

    String gerbs = keyboard.nextLine();
    int numGerbs = Integer.parseInt(gerbs);
    String gerbIDs[] = new String[numGerbs];
    String gerbNNs[] = new String[numGerbs];
    int gerbEat[] = new int[numGerbs];
    int k = 1;
    int arraycount = 0;
    int l = 0;

    for (int i = 0; i < numGerbs; i++)
    {
        System.out.println("Gerbil " +k +"'s lab id:");
        gerbIDs[i] = keyboard.nextLine();
        System.out.println("What name did the undergrads give to " +gerbIDs[i] +"?");
        gerbNNs[i] = keyboard.nextLine();
        System.out.println(gerbIDs[arraycount] +" eats how many " +foodNames[arraycount] +" per day?");
        String gerbConsump = keyboard.nextLine();
        int gerbEat1 = Integer.parseInt(gerbConsump);
        gerbEat[l] = gerbEat1;
        System.out.println(gerbIDs[arraycount] +" eats how many " +foodNames[arraycount + 1] +" per day?");
        String gerbConsump2 = keyboard.nextLine();
        int gerbEat2 = Integer.parseInt(gerbConsump2);
        gerbEat[l+1] = gerbEat2;

        k++;
    }

    //ONLY PROBLEM IS THE PROGRAM DOESN'T CHANGE GERBIL NAME WHEN LOOPING
    System.out.println(Arrays.toString(foodNames));
    System.out.println(Arrays.toString(foodMax));
    System.out.println(Arrays.toString(gerbIDs));
    System.out.println(Arrays.toString(gerbNNs));
    System.out.println(Arrays.toString(gerbEat));
}

}

The problem is in these lines:

System.out.println(gerbIDs[arraycount] +" eats how many " +
                   foodNames[arraycount] +" per day?");
String gerbConsump = keyboard.nextLine();
int gerbEat1 = Integer.parseInt(gerbConsump);
gerbEat[l] = gerbEat1;
System.out.println(gerbIDs[arraycount] +" eats how many " +
                  foodNames[arraycount + 1] +" per day?");

Replace arrayCount in gerbIDs with i .

There are some other problems that may or may not occur if you were to potentially go out of bounds in foodNames . You use arraycount + 1 and that could cause you to go beyond the end of the array. It also does not appear that you increment l at all.

You're dealing with the assignment in a very procedural way. I don't know what your teacher expects of you, but you should probably create classes representing FoodType and Gerbil .

That being said, here is some insight.

The problems

1. Nested loop needed

The first problem is that you don't use a nested loop regarding the food the gerbils eat. Since the number of types of food is dynamic (given by the user), you need to ask for input as many times as the number of different types.

You're currently repeating the prompting code twice: this only works if there are 2 types of food. Instead, use a for loop that iterates on the types of food.

2. Array indices messed up: j , k , l , and arrayCount not needed

Keep in mind what you are iterating on:

  • the gerbils (in the arrays gerbNNs and gerbIDs )
  • the food types (in the arrays foodNames and foodMax )

Therefore, only 2 indices are needed: for instance g (gerbil) and ft (foodtype).

Also, j and k are just here to provide a 1-based version of the loop index i , you should instead use i+1 . These variables are definitely not needed and they make the code needlessly harder to read.

3. The gerbils food consumption

This line is wrong:

int gerbEat[] = new int[numGerbs];

What you are trying to store is the daily consumption of one type of food by one gerbil . This means you need a two dimensional array, indexed by the two indices I talked about in the previous section:

int[][] gerbEat = new int[numGerbs][foodNum];

Then you can access the daily consumption of food ft by gerbil g with the expression:

gerbEat[g][ft]

A solution

Here is your code with the modifications I talked about in the previous part:

String diffFoods = keyboard.nextLine();
int foodNum = Integer.parseInt(diffFoods);
String foodNames[] = new String[foodNum];
int foodMax[] = new int[foodNum];

for (int ft = 0; ft < foodNum; ft++) {
    System.out.println("Name of food item " + (ft+1) +":");
    foodNames[ft] = keyboard.nextLine();
    System.out.println("Maximum consumed per gerbil:");
    String maxCons = keyboard.nextLine();
    foodMax[ft] = Integer.parseInt(maxCons);
}

System.out.println("How many gerbils are in the lab?");
String gerbs = keyboard.nextLine();
int numGerbs = Integer.parseInt(gerbs);
String gerbIDs[] = new String[numGerbs];
String gerbNNs[] = new String[numGerbs];
int[][] gerbEat = new int[numGerbs][foodNum];

for (int g = 0; g < numGerbs; g++) {
    System.out.println("Gerbil " + (g+1) +"'s lab id:");
    gerbIDs[g] = keyboard.nextLine();
    System.out.println("What name did the undergrads give to " +gerbIDs[g] +"?");
    gerbNNs[g] = keyboard.nextLine();
    for (int ft = 0; ft < foodNum; ft++) {
        System.out.println(gerbIDs[g] +" eats how many " + foodNames[ft] +" per day?");
        String gerbConsump = keyboard.nextLine();
        int gerbEat1 = Integer.parseInt(gerbConsump);
        gerbEat[g][ft] = gerbEat1;
    }
}

UPDATE: in response to your comment

What I mean in the first lines of my posts is that, instead of having several global arrays qualifying different aspects of entities (such as the gerbils), you should use a single array of objects that represent these entities.

For instance, you need several elements about your gerbils:

  • ID
  • nickname
  • daily food consumption
  • whether they have a tendency to escape
  • whether they bite
  • maybe some other stuff later on...

So you should create a class for that:

class Gerbil {
    String id;
    String nickname;
    boolean bites;
    boolean escapes;
    int[] dailyFoodQuantity;
}

Why should you do so? Because it makes sense to gather information about an entity, and abstract it. If you need to return some Gerbil's information, just return the Gerbil object, and all is there. The using code asking for a gerbil does not need to use every aspect of it.

Also, if some aspect was forgotten about an entity, you can just add a field and it creates no problem (no need to add parameters to any method or anything).

I am not sure exactly what you intended here, but i imagine that your problem is that you have forgotten to increment arraycount, since it doesn't really make sense that you define that to be zero throughout your program. You also don't appear to increment l. If these are constants, define them as such by adding final to the declaration.

You also seem to have some confusion, there is no need to have counters inside the for loops, you can use the int i defined in the for loop. eg

for(int i=0; i<10; i++){
    System.out.println(i);
}

will print 0,1,2,3 etc. It also makes your code much more readable. Any counter in a for loop which has a predictable dependency on the loop counter should be incremented with i. This makes it easier to read. Also, consider the layout of your code: large blocks with no comments and no new lines make it hard to understand what is going on, not such a problem in this simple example, but good practice is important. Organise your code into blocks which have a single logical goal, and above them add a comment saying what that goal is.

Also, in the case that you are defining random ints either use a self explanatory name, or make a comment, so you can see exactly what, eg k, is supposed to be used for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM