我正在尝试调用 StudentScore
类中的 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);
}
最佳答案
如果您的循环从 j=0
开始,并且您访问列表中 j-1
处的元素,您将看到问题出在哪里。
当j=0
时,您尝试访问-1
。没有索引-1。因此出现了错误。从 j=1
开始解决了这个问题。
这有什么帮助吗?
关于java - 在对象的数组列表中查找最小值,无法比较数组列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189556/