首页 > 解决方案 > java 2d 数组上的 java.lang.ArrayIndexOutOfBoundsException

问题描述

公共类波音座位图扩展座位图{

public BoeingSeatMap() {
    this.seats= new Seat[nRows][nColumns] ;
    this.nColumns=7;
    this.nRows=10;
    this.nFirstClassRows=4;
    initialiseSeatMap();
}
protected void initialiseSeatMap() {
    String str="ABCDEFG";

    for (int i=0;i<nRows;i++) {
        seats[i][0].getSeatPostion().setRow(i+1);
        seats[i][0].getSeatPostion().setColumn(str.charAt(0));
        seats[i][0].setSeatType(SeatType.WINDOW);

        seats[i][nColumns-1].getSeatPostion().setRow(i+1);
        seats[i][nColumns-1].getSeatPostion().setColumn(str.charAt(6));
        seats[i][nColumns-1].setSeatType(SeatType.WINDOW);
        if (i<=4) {
            seats[i][0].setFirstClass(true);
            seats[i][nColumns-1].setFirstClass(true);
        }
    }

只是想知道为什么当我尝试存储到不应超出范围的二维数组的一部分时,这会返回 ArrayIndexOutOfBoundsException,例如 [1][6]

标签: java

解决方案


您没有包括整个班级,但据我所知,您在“座位”之后实例化了“nColumns”和“nRows”。尝试修改构造函数:

public BoeingSeatMap() {
    this.nColumns=7;
    this.nRows=10;
    this.seats= new Seat[nRows][nColumns] ;
    this.nFirstClassRows=4;
    initialiseSeatMap();
}

推荐阅读