user3430421
user3430421

Reputation: 31

java.lang.OutOfMemoryError: Java heap space. From trying to add scanner input values to an ArrayList

Not sure why I'm getting this weird error, but the program does not compile either so there must be something wrong with the while loop I made for the scanner. I've never seen this particular error.

private ArrayList gradeList;

public GradeDistribution() {
   this.gradeList = new ArrayList<Integer>();
}

public void addGrades(Scanner reader) {
    int grade = Integer.parseInt(reader.nextLine());
    while (true) {
        if (grade == -1) {
            this.printGrades();
            break;
        } else {
            this.gradeList.add(grade); //the error points to this line
        }
    }
}

I did not include the printGrades() method but I assure you it is not the source of the problem. I have no idea what I'm doing wrong as everything seems like it should work. The ArrayList is initialized so I know it's not that...

Upvotes: 0

Views: 766

Answers (1)

Leri
Leri

Reputation: 12535

You need to move:

int grade = Integer.parseInt(reader.nextLine());

inside while loop.

Otherwise you have infinite loop that tries to infinitely add value of variable grade to gradeList. This increases allocated size on every iteration and when it exceeds limit exception is thrown.

When you move int grade = Integer.parseInt(reader.nextLine()); inside loop it (reader.nextLine()) will stop loop until user hits enter.

After change your code will become:

public void addGrades(Scanner reader) {
    while (true) {
        int grade = Integer.parseInt(reader.nextLine());

        if (grade == -1) {
            this.printGrades();
            break;
        } else {
            this.gradeList.add(grade); //the error points to this line
        }
    }
}

Upvotes: 5

Related Questions