java.lang.OutOfMemoryError:java堆空间。从尝试将扫描仪输入值添加到ArrayList

java.lang.OutOfMemoryError:java堆空间。从尝试将扫描仪输入值添加到ArrayList,java,arraylist,out-of-memory,Java,Arraylist,Out Of Memory,我不知道为什么会出现这个奇怪的错误,但是程序也没有编译,所以我为扫描仪做的while循环肯定有问题。我从未见过这种特殊的错误 私有ArrayList成绩表 public GradeDistribution() { this.gradeList = new ArrayList<Integer>(); } public void addGrades(Scanner reader) { int grade = Integer.parseInt(reader.nextLine

我不知道为什么会出现这个奇怪的错误,但是程序也没有编译,所以我为扫描仪做的while循环肯定有问题。我从未见过这种特殊的错误

私有ArrayList成绩表

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
        }
    }
}
public-grade-distribution(){
this.gradeList=新的ArrayList();
}
公共图书馆(扫描器){
int grade=Integer.parseInt(reader.nextLine());
while(true){
如果(等级==-1){
这个.printGrades();
打破
}否则{
this.gradeList.add(grade);//错误指向此行
}
}
}
我没有包括printGrades()方法,但我向您保证这不是问题的根源。我不知道我做错了什么,因为一切似乎都应该起作用。ArrayList已初始化,因此我知道不是…

您需要移动:

int grade = Integer.parseInt(reader.nextLine());
内部,而
循环

否则,您将有一个无限循环,它试图无限地将变量
grade
的值添加到
gradeList
。这会在每次迭代时增加分配的大小,当它超过限制时,会抛出异常

当您移动
int grade=Integer.parseInt(reader.nextLine())时内部循环它()将停止循环,直到用户点击回车键

更改后,您的代码将变为:

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
        }
    }
}
您需要移动:

int grade = Integer.parseInt(reader.nextLine());
内部,而
循环

否则,您将有一个无限循环,它试图无限地将变量
grade
的值添加到
gradeList
。这会在每次迭代时增加分配的大小,当它超过限制时,会抛出异常

当您移动
int grade=Integer.parseInt(reader.nextLine())时内部循环它()将停止循环,直到用户点击回车键

更改后,您的代码将变为:

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

当然这有点令人沮丧,因为这在过去对我来说是非常明显的;过去一周我的工作一直停滞不前。谢谢,不客气。如果这解决了你的问题,你应该接受它。在左边打勾。当然!这有点令人沮丧,因为这在过去对我来说是非常明显的;过去一周我的工作一直停滞不前。谢谢,不客气。如果这解决了你的问题,你应该接受它。在左边打勾。