在对象的 Arraylist 中查找 min,无法比较 arraylist 中的元素

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

我正在尝试调用 StudentScore class 中的 getScore() 方法来确定 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);

    }

拜托,

变化自

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

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

如果您的循环从 j=0 开始,并且您访问列表中 j-1 处的元素,您将看到问题出在哪里。

j=0 时,您尝试访问 -1。没有索引-1。因此错误。从 j=1 开始解决这个问题。

这有什么帮助吗?

无法仅通过比较相邻值来找到序列的min/max。
您必须将值与 min/max-到目前为止的值进行比较。

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