na wa
na wa

Reputation: 3

java.lang.ArrayIndexOutOfBoundsException on a java 2d Array

public class BoeingSeatMap extends SeatMap{

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

Just wondering why this would return a ArrayIndexOutOfBoundsException when I am trying to store into a part of the 2d array that shouldnt be out of bounds eg [1][6]

Upvotes: 0

Views: 39

Answers (2)

Alexandr Ivanov
Alexandr Ivanov

Reputation: 399

You must initialize nColumns and nRows fields before you create seats array.

Upvotes: 0

Oboe
Oboe

Reputation: 2723

You didn't include the entire class, but from what I can see you are instantiating "nColumns" and "nRows" afters "seats". Try modifying the constructor:

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

Upvotes: 2

Related Questions