[英]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.