我正在尝试以网格4列X 5行的形状创建一个地图,并将每个房间连接在一起。下面的代码编译,但当我尝试运行它时,它会出现错误。有谁能告诉我哪里出了问题?谢谢。
public static final int NUM_ROOMS = 20;
public static final int NUM_COLS = 4;
private ArrayList<Room> myRooms;
public Map(){
int row =0;
ArrayList<Room> myRooms = new ArrayList<Room>();
while (row<NUM_COLS){
int i =0;
i = row % NUM_COLS;
while(i+1<NUM_COLS){
while (i+1 <(row+1)% NUM_COLS){
Room r1 = myRooms.get(i);
Room r2 = myRooms.get(i+1);
r1.connectTo(r2);
r2.connectTo(r1);
i++;
}
row++;
}
int col = 0;
while (col<NUM_COLS){
i = col;
while (i+4<NUM_ROOMS){
i = i+NUM_COLS;
}
col++;
}
}
}
答案 0 :(得分:1)
问题是myRooms
列表为空。因此,当您尝试从列表中获取元素时,会出现异常。你必须使用像
for (int i = 0; i < NUM_ROOMS; i++) {
myRooms.add(new Room());
}
首先填充列表。