Paul
Paul

Reputation: 142

Adding a specific range of numbers to an array

I have been looking and looking at my code and I still can't figure out why the result is always the highestGrade value and not a different value for every position in the array.

Here is my code:

int[] gradesDescription;
int[] gradesCount;

gradesDescription = new int[(highestGrade-lowestGrade) + 1];
gradesCount = new int[(highestGrade-lowestGrade) + 1];

for(int b = lowestGrade; b <= highestGrade; b++){
  Arrays.fill(gradesDescription, b);
}

for(int d = 0; d < gradesDescription.length; d++){
 System.out.println("Grade: " + gradesDescription[d] + 
                    " had " + gradesCount[d] + " students with the same grade.");

What is the logic that I am missing; is there a better way on how to accomplish what I am trying to do?

Thanks so much!

Upvotes: 1

Views: 1540

Answers (3)

dbyrne
dbyrne

Reputation: 61011

This line is causing your problem:

Arrays.fill(gradesDescription, b);

This will assign EVERY value in gradesDescription to b. What you want instead is something like:

for(int b = 0; b < gradesDescription.length; b++) {
    gradesDescription[b] = b + lowestGrade;
}

Although, I have to say even this code looks wrong. What is the expected behavior if there are three students with grades of 70, 80, and 100? gradesDescription.length will end up being 30, but really it should only be 3? I'm assuming you left out the code where the elements of gradesCount are assigned?

Upvotes: 2

pmorken
pmorken

Reputation: 784

Arrays.fill is filling the entire array with the same value each time through the loop. I think you wanted

for(int idx = 0; idx < gradesDescription.length; idx++){
  gradesDescription[idx] = idx + lowestGrade;
}

Upvotes: 1

christopher
christopher

Reputation: 27336

for(int b = lowestGrade; b <= highestGrade; b++){
     Arrays.fill(gradesDescription, b);
}

This line will place the value in b at every position in your gradesDescription array. Hence the same value every time.

Upvotes: 2

Related Questions