向数组添加特定范围的数字

时间:2013-05-01 21:10:41

标签: java arrays

我一直在寻找并查看我的代码,我仍然无法弄清楚为什么结果始终是最高值,而不是数组中每个位置的不同值。

这是我的代码:

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

我缺少的逻辑是什么;有没有更好的方法来完成我想要做的事情?

非常感谢!

3 个答案:

答案 0 :(得分:2)

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

此行会将b中的值放在gradesDescription数组中的每个位置。因此,每次都有相同的价值。

答案 1 :(得分:2)

此行导致您的问题:

Arrays.fill(gradesDescription, b);

这会将gradesDescription中的每个值分配给b。你想要的是:

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

虽然,我不得不说这个代码看起来不对。如果有三个学生的成绩分别为70,80和100,那么预期的行为是什么? gradesDescription.length最终会达到30,但实际上它应该只有3?我假设您遗漏了分配gradesCount元素的代码?

答案 2 :(得分:1)

每次循环时,Arrays.fill都会使用相同的值填充整个数组。我想你想要

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