我一直在查看我的代码,但我仍然无法弄清楚为什么结果总是最高等级值,而不是数组中每个位置的不同值。
这是我的代码:
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.");
我缺少的逻辑是什么;有没有更好的方法来完成我想做的事情?
非常感谢!
最佳答案
这一行导致了您的问题:
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
元素的代码?
关于java - 将特定范围的数字添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16326578/