簡體   English   中英

在對象的Arraylist中查找min,無法比較arraylist中的元素

[英]Find min in Arraylist of object, can't compare the elements in an arraylist

我試圖調用getScore()方法在我StudentScore類,以確定過元素的最小和最大ArrayList中,內printStat()下面介紹方法。 我得到一個ArrayIndexOutOfBoundException 這是什么意思,我該如何解決?

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

    }

如果循環從j=0開始,則訪問列表中j-1處的元素,您將看到問題所在。

j=0 ,您嘗試訪問-1 沒有索引-1。 因此,錯誤。 j=1解決了這個問題。

這有什么幫助嗎?

請,

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

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

不能僅通過比較相鄰的找到序列的最小值/最大值。
您必須將值與最小/最大到目前為止的值進行比較。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM