java中的2D对象数组

时间:2016-03-04 12:57:06

标签: java arrays object multidimensional-array interface

我想创建由接口Field实现的2D对象数组,但它不会通过编译运行。我得到的错误是java.lang.ArrayIndexOutOfBoundsException: 9在我指定this.field[i][j] = this.border的行上。 Theese是我的档案:

Board.java:

package board;

public class Board {
private int size;
private Field [][] field;
private BoardField board;
private  BorderField border;

    public Board(int size){
    this.field = new Field[size+1][size+1];
    this.size = size;

    for(int i = 0; i <= size +1; i++){
        for(int j = 0; i <= size +1; j++){
            if(i == 0 || j == 0 || (i == size +1) || (j == size +1)){
                this.border =  new BorderField();
                this.field[i][j] = this.border;
            }
            else {
                this.board = new BoardField(i, j);
                this.field[i][j] = this.boar;
            }
        }
     }
  }

   public static void main (String[] args)
   {
       Board board = new Board(8);
   }
}

BoardField.java:

package board;

public class BoardField implements Field {
boolean diskOnField;
int row;
int col;

    public BoardField(int row, int col){
    this.row = row;
    this.col = col;
    diskOnField = false;
    }
}

BoardField.java:

package board;

public class BorderField implements Field {
public BorderField(){}
}

Field.java:

package board;

public interface Field {
    public static enum Direction {
        L,LU,U,RU,R,RD,D,LD;
    }
}

1 个答案:

答案 0 :(得分:0)

您已分配this.field = new Field[size+1][size+1];,因此this.field[size+1]超出范围,您无法在不抛出异常的情况下访问它。

也许您想要这样:(将size+1更改为size

for(int i = 0; i <= size; i++){
    for(int j = 0; i <= size; j++){
        if(i == 0 || j == 0 || (i == size) || (j == size)){
            this.border =  new BorderField();
            this.field[i][j] = this.border;
        }
        else {
            this.board = new BoardField(i, j);
            this.field[i][j] = this.boar;
        }
    }
 }