2016-03-23 23 views
0

Ben aşağıda sunulmuştur printStat() yöntemi içinde, bir ArrayList elemanların üzerinde minimum ve maksimum belirlemek için benim StudentScore sınıfında getScore() yöntemi çağırmak çalışıyorum . Bir ArrayIndexOutOfBoundException alıyorum. Bu ne anlama geliyor ve sorunu nasıl çözebilirim?bir arraylist unsurları karşılaştırmak olamaz, nesnenin Arraylist içinde min bulun

public class ScoreCalculator{ 
    private int[] scoreCounter; 
    ArrayList<StudentScore> scores ; 

    public ScoreCalculator(int maxScore) { 
     scoreCounter = new int[maxScore]; 
     scores = new ArrayList<StudentScore>(maxScore); 
    } 

    public void printStat() { 
     System.out.println("Score Report for " + scores.size() + " Students "); 

     min = 0; 
     max = 0; 
     int j=0; 

     for (j = 0; j < scores.size(); j++) { 

      if (scores.get(j).getScore() < scores.get(j - 1).getScore()) { 
       min = scores.get(j).getScore(); 
      } 
      if (scores.get(j).getScore() > scores.get(j - 1).getScore()) { 
       max = scores.get(j).getScore(); 
      } 
     } 

     System.out.println(min); 
     System.out.println(max); 

    } 
+0

'j-1' Kodunuzdaki negatif olabilir, endeks aralığı boyut() -1 ile 0, negatif değer izin verilmez – haifzhan

+0

Sen eleman' j-1' de erişir. Listenizi sipariş etmenizi öneririm, böylece ilk öğe "min" ve sonuncudur "max". –

cevap

1

için

for(j=0;j<scores.size();j++){ 

den

değişiklik döngü formunu j=0 başlar ve listedeki j-1 de öğeye erişmek için, olacak sorunun nerede olduğunu görün.

j=0, -1'a erişmeyi deneyin. İndeks -1 yok. Bu yüzden hata. j=1'dan başlayarak bunu çözer.

Bu, herhangi bir şekilde yardımcı olur mu?

0

lütfen

for(j=1;j<scores.size();j++){ 
0

Sen sadece değerleri komşu karşılaştırarak bir dizinin min/max bulamıyorum.
Değerleri min/maks-so-far ile karşılaştırmalısınız.

if (scores.isEmpty()) 
    throw new IllegalStateException("No scores found"); 
int min = scores.get(0).getScore(); 
int max = min; 
for (int j = 1; j < scores.size(); j++) { 
    int score = scores.get(j).getScore(); 
    if (score < min) 
     min = score; 
    if (score > max) 
     max = score; 
}