为什么会出现数组越界问题?

package rectangle;

public class rectangleTest {
static int length = 8;
static int value = 1;
static int[][] arr = new int[length][length];
static direction lastdirection = direction.Right;
public static void main(String[] args) {
iniarrary();
print(arr);
}
public enum direction{
Right,Left,Down,Up;
}

public static void iniarrary(){
int row=0,col=0;

for(int c=0;c<length*length;c++){

arr[row][col] = value;
lastdirection = findDirection(row,col);
switch(lastdirection){
case Right:
col++;
break;
case Down:
row++;
break;
case Left:
col--;
break;
case Up:
row--;
break;
default:
System.out.println("error");
}

value++;
}

}
public static direction findDirection(int row,int col){
direction Direction = lastdirection;
switch(Direction){
case Right:
if((col==length-1)||(arr[row][col+1]!=0)){
Direction = direction.Down;
break;
}
case Down:
if((row==length-1)||(arr[row+1][col]!=0)){
Direction = direction.Left;
break;
}
case Left:
if(row==0){
//Direction = direction.Up;
break;
}else if(arr[row-1][col]!=0){
Direction = direction.Up;
break;
}
case Up:
if(((row==0)&&(col==0)))
{
Direction = direction.Right;
break;
}
}

    return Direction;
}


public static void print(int[][] arr){
    for (int i=0;i<length;i++){
        for(int j=0;j<length;j++){

            System.out.printf("%2d",arr[i][j]);

        }
        System.out.println();
    }

}   

}

运行时出现以下错误,是为什么?是这个原因吗if(arr[row-1][col]!=0){
Direction = direction.Up;
break;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at rectangle.rectangleTest.iniarrary(rectangleTest.java:18)
at rectangle.rectangleTest.main(rectangleTest.java:9)

iniarray方法中的for循环for(int c=0;c<length*length;c++){ 应该是 c<length

你对行列值做了限制但是在函数中没有设计边界条件。

数组越界很明显是因为你外层循环是length*length的,而你的行row和col的最大边界只是length的。
你初始化时整个length*length范围内导致了行列越界。

你里面的row--和col--之后要判断是否小于0