首页 > 解决方案 > 尽管我确保数组索引小于数组大小,但如何修复数组索引超出范围?

问题描述

我创建了一个名为 Matrix 的类,在其中借助一些方法,我可以将矩阵的顺序和矩阵的元素作为用户的输入。当我运行代码时,它要求我输入矩阵的顺序,然后不是要求我输入矩阵的元素,而是给出错误“java.lang.ArrayIndexOutOfBoundsException”。你可以看看代码。

  import java.util.Scanner;

  public class Matrix {
      int mRow;
      int nColumn;

      Scanner input = new Scanner(System.in);

      void getInput() {
          System.out.println("Enter number of rows:");
          mRow = input.nextInt();
          System.out.println("Enter number of columns:");
          nColumn = input.nextInt();
      }

      int a[][] = new int[mRow][nColumn];

      void getElement() {
          System.out.println("Enter the elements of the matrix: ");
          for (int i = 0; i < mRow; i++) {
              for (int j = 0; j < nColumn; j++) {
                  a[i][j] = input.nextInt();
              }
          }
      }

      void showMatrix() {
          for (int i = 0; i < mRow; i++) {
              for (int j = 0; j < nColumn; j++) {
                  System.out.print(a[i][j] + " ");
              }
            System.out.println();
        }
    }
}

在此处输入图像描述

  [1]: https://i.stack.imgur.com/guyRk.png

标签: javaobject

解决方案


确保在收到输入时更新数组,即。

void getInput() {
    System.out.println("Enter number of rows:");
    mRow = input.nextInt();
    System.out.println("Enter number of columns:");
    nColumn = input.nextInt();
    a = new int[mRow][nColumn]; // you need this line
}

推荐阅读