2013-05-01 69 views
1

我一直在尋找並查看我的代碼,我仍然無法弄清楚爲什麼結果總是最高的值,而不是數組中每個位置的不同值。向數組中添加特定範圍的數字

這裏是我的代碼:

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

是什麼,我缺少的邏輯;有沒有更好的方法來完成我想要做的事情?

非常感謝!

回答

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的元素被分配的代碼?

+0

很好的描述!我現在得到了邏輯,我也看到Arrays.fill只是發送相同的值到我的數組。謝謝! – Paul 2013-05-01 21:20:32

+0

我正在使用一個不同的數組來通過一個包含特定成績的文件,並且我需要計算每個年級有多少同學獲得相同成績(範圍介於lowestGrade到highestGrade之間),然後我將每個計數分配給相應的位置,匹配gradesDescription。然後,我將打印相同等級的學生的成績和數量。 – Paul 2013-05-01 21:25:48

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

這條線將放在b值在你gradesDescription陣列的每個位置。因此每次都有相同的值。

1

Arrays.fill在每次通過循環時用相同的值填充整個數組。我想你想

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