尽管循环在数组长度范围内,但仍出现越界异常

Out of bounds exception despite loops being in range of array length

所以程序应该根据用户输入创建一个大小在 3 到 11 之间的奇数数组,然后在特定位置用字符填充该板以获得模式。一切都很顺利,直到我尝试返回数组,即使我将循环设置为小于维度,它也给了我 2 个越界异常。我在这里以 5 为例来尝试获得一个 5 x 5 的数组。这是主要的。

public static void main (String [] args) {

    int dimension = findDimension();
    char [] [] array2d = new char [dimension] [dimension];

    char star = '*';

    array2d = leftDiagonal(star, dimension); // Get out of bounds here
    print(array2d); 
} 

要求用户输入的方法"findDimension()"

public static int findDimension() {
    int dimension = 0;
    Scanner keybd = new Scanner(System.in); 
    do {
        System.out.print("Enter an odd integer between 3 and 11 please: ");
        dimension = keybd.nextInt();
    } while (dimension%2 == 0);
    return dimension;            // Everything seems fine here, no errors
}

打印数组的方法

public static void print(char [] [] arrayParam) {
    System.out.println("-----------");
    System.out.println(arrayParam);
    System.out.println("-----------");
}

设置模式的方法"leftDiagonal"

public static char [] [] leftDiagonal(char starParam, int dimenParam) {
    char [] [] leftD = new char [dimenParam] [dimenParam];
    for (int i = 0; i < dimenParam; i++){ 
        for (int j = 0; i < dimenParam; j++) {
            leftD [i][j] = starParam;  // Gets error here
        }
    }
    return leftD;
}

输出应该是

-----------                             
 * * * * *
 * * * * *
 * * * * *
 * * * * *
 * * * * *
----------- 

从技术上讲应该是

 -----------                             
  *    
    *   
      *  
        * 
          *
 -----------  

但目前我只想获得任何输出。我原本打算用空格 ' ' 填充所有空间,然后用字符填充我需要的空间,但我什至无法先打印出数组。感谢任何愿意提供帮助的人。

由于内部循环条件发生错误。

public static char[][] leftDiagonal(char starParam, int dimenParam) {
    char[][] leftD = new char[dimenParam][dimenParam];
    for (int i = 0; i < dimenParam; i++) {
        for (int j = 0; j < dimenParam; j++) { // i -> j
            leftD[i][j] = starParam;  // Gets error here
        }
    }
    return leftD;
}

解决问题的方法有很多种。 您可以只打印数组而不对其进行初始化。

public static char[][] leftDiagonal(char starParam, int dimenParam) {
    char[][] leftD = new char[dimenParam][dimenParam];
    for (int i = 0; i < dimenParam; i++) {
        for (int j = 0; j < dimenParam; j++) {
            if(i==j) {
                System.out.print(starParam);
            } else {
                System.out.print("  ");
            }
        }
        System.out.println();
    }
    return leftD;
}