-1

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

}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
SABR30
  • 11
  • 1
  • 1
    Can you explain us in your own words what is wrong? What test sample did you try and what did you expect? What did you actually get? Logically wrong results or errors/exceptions? – But I'm Not A Wrapper Class Apr 15 '14 at 14:50
  • Works here: http://pastebin.com/6NJDWU8u – Engineer2021 Apr 15 '14 at 14:50
  • 4
    I dont see a step 4, I think you duplicated your links to the pics. Only a step 6, and part of what I assume is step 5. – Mark W Apr 15 '14 at 14:50
  • 1
    Do a very simple problem, with e.g. only two array elements, stepping through your code with paper and pencil. If in doubt, add System.out.println or similar calls to your code to show you what it does. – Patricia Shanahan Apr 15 '14 at 14:54
  • @staticx My problem is in that in lines 21 and 23 of the post they are supposed to say brian but in lines 29 and 30 they are supposed to say richard. – SABR30 Apr 15 '14 at 15:06
  • @SABR30: I found your problem – Engineer2021 Apr 15 '14 at 15:09
  • Just a side note: if the purpose of `j` and `k` is just to provide a 1-based version of the loop index, you should instead use `i+1`. – Joffrey Apr 15 '14 at 15:34

3 Answers3

0

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.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51
  • That's what I did at first but here's what happens vs what is supposed to happen: http://postimg.org/image/frcvvx0dt/ I basically don't understand how to write the loop while filling out my arrays. – SABR30 Apr 15 '14 at 15:20
0

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).

Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • Thank you! Do you have link to help me better understand how to use nested loops? And can you further clarify what you mean by creating separate classes. I have an assignment that I completed where I have the user call for a class kind of like what my instructor wants in steps 5 & 6 however, I didn't quite understand what the purpose is of creating the two separate classes "FoodType" and "Gerbil". – SABR30 Apr 15 '14 at 18:24
  • @SABR30 The upvote is the accepted way of saying thanks here ;) I updated my post to answer your questions about classes. As for nested loops, it is just a loop inside another loop, like the one I provided in my answer. – Joffrey Apr 15 '14 at 23:44
  • @SABR30 Maybe the `FoodType` class is not much needed, it depends if it makes things simpler or more complicated. – Joffrey Apr 15 '14 at 23:51
  • @SABR30 If you're still curious about nested `for` loops, here is the simplest example I found: http://stackoverflow.com/questions/656747/simple-nested-for-loop-example – Joffrey Apr 15 '14 at 23:56
-1

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. e.g.

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, e.g. k, is supposed to be used for.

phil_20686
  • 4,000
  • 21
  • 38
  • Why is this answer downvoted? It seems quite correct IMHO. Would the downvoter care to comment please? – Joffrey Apr 15 '14 at 15:32
  • @Joffrey i didn't downvote but this didn't help me (most likely due to my lack of clarification). Any ideas?: http://postimg.org/image/frcvvx0dt/ – SABR30 Apr 15 '14 at 15:34
  • @SABR30 I do have an idea, take a look at my edited answer ;) – Joffrey Apr 15 '14 at 16:02