我正在尝试引用我在方法中启动的arraylist,但是当我尝试从该ArrayList中删除某些东西时,我得到一个错误,说我的ArrayList的大小为0.但是,在我设置之后在ArrayList的值中,它打印出ArrayList的大小,我称之为'school'。这是我的代码。
import java.util.*;
public class SchoolSolver{
public static ArrayList<Girl> school = new ArrayList<Girl>();
public static ArrayList<Girl> used = new ArrayList<Girl>();
public static void main(String[] args){
resetSchool();
//System.out.println(school.size());
boolean notPossible = false;
for(int i = 0; i < 7; i++){
if(notPossible){
resetSchool();
} else {
newDay();
}
for(int j = 0; j < 5; i++){
//randomGirl() is where my error happens
Girl leader = randomGirl();
used.add(leader);
}
}
}
/*Below are the two methods where I suspect the error may originate from */
public static void resetSchool(){
school.clear();
for(int i = 0; i < 15; i++){
//System.out.println("ran");
school.add(new Girl(i));
}
for(Girl g : school){
ArrayList<Girl> classmates = new ArrayList<Girl>();
for(int i = 0; i < 15; i++){
if(i!= g.getID()){
classmates.add(new Girl(i));
}
}
g.setClassmates(classmates);
}
}
public static Girl randomGirl(){
return school.remove(0);
}
谢谢,我感谢您的帮助!
答案 0 :(得分:2)
你有一个永无止境的循环
for(int j = 0; j < 5; i++)
了解如何增加i
而不是j
。这意味着您继续调用randomGirl
,每次调用时都会从列表中删除Girl
。所以过了一会儿(15次)你的列表变空了,你仍然会调用randomGirl
,这会导致异常