Karos papermoon
Karos papermoon

Reputation: 69

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

I'm trying to invoke the getScore() method in my StudentScore class to determine the min and max over elements in an ArrayList, within the printStat() method presented below. I'm getting an ArrayIndexOutOfBoundException. What does that mean, and how can I fix the problem?

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

    }

Upvotes: 0

Views: 249

Answers (3)

Andreas
Andreas

Reputation: 159086

You cannot find the min/max of a sequence by only comparing neighboring values.
You have to compare values to the min/max-so-far.

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

Upvotes: 0

Debosmit Ray
Debosmit Ray

Reputation: 5403

If your loop starts form j=0, and you access the element at j-1 in the list, you will see where the issue is.

When j=0, you try to access -1. There is no index -1. Hence the error. Starting from j=1 solves this.

Does this help in any way?

Upvotes: 1

Vishal Gajera
Vishal Gajera

Reputation: 4207

please,

change from

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

to

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

Upvotes: 0

Related Questions