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

标签 java arrays char 2d indexoutofboundsexception

因此,该程序应该根据用户输入创建一个大小介于 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;
}

关于java - 尽管循环在数组长度范围内,但仍出现越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738485/

相关文章:

java - 当 JUnit 类具有多个导入时,如何从 Windows CMD 窗口运行 JUnit 测试?

java - 如何更改两个字符串之间的字符?

java - Eclipse 中的 Maven 在 POM 更改时提示 "Unable to locate the Javac Compiler"

java - 点击自定义时如何关闭JCombobox的下拉列表?

arrays - 在 Swift 中定义数组

php - 在 PHP 中限制数组的长度

c - 有没有办法检查 C 字符串中是否存在任何或所有字符?

c++ - 为什么角色在与他们打交道后会像 � 一样出现?

java - 尝试在服务和另一个类之间 bundle 额外内容时出现 NullPointerException

c - 我必须将用户输入的 10 个值读取到一个数组中,然后用 C 打印它们