【问题标题】:Exception in thread not be able to read values in constructors线程中的异常无法读取构造函数中的值
【发布时间】:2021-02-01 23:08:50
【问题描述】:

线程“main”java.lang.ArrayIndexOutOfBoundsException 中的异常:索引 0 超出长度范围;

    import java.util.Scanner;

//import jdk.javadoc.internal.doclets.formats.html.SourceToHTMLConverter;

class checkMatrix1 {
    int row;
    int column;
    int[][] matrix = new int[row][column];

    public checkMatrix1(int row, int column) {
        this.row = row;
        this.column = column;
    }
    public checkMatrix1() {
        this.row = 3;
        this.column = 3;
    }
}

public class test{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println(" Enter Row: ");
        System.out.println(" Enter Column: ");
        int row = input.nextInt();
        int column = input.nextInt();
        checkMatrix1 matrix1 = new checkMatrix1(row, column);

        for (int i = 0; i < matrix1.row; i++) {
            for (int j = 0; j < matrix1.column; j++) {
                System.out.println(matrix1.matrix[i][j]);
            }
        }
    }
}

我无法从用户那里读取构造函数中的值

【问题讨论】:

  • 该错误发生在哪一行? int[][] 矩阵 = new int[row][column];这不受您发送给构造函数的影响,因此它始终为空。可能不是你想要的

标签: java exception


【解决方案1】:

首先运行字段初始值设定项,然后运行构造函数。所以,如果你打电话给new checkMatrix(2, 2);

int row;

行现在是 0。

int column;

列现在为 0。

int[][] matrix = new int[row][column];

矩阵现在是一个 0 x 0 数组。

现在我们转到构造函数中的行..

this.row = row;

this.column = column;

row 和 colum 现在是 2。不过,new int[][] 声明为时已晚。

new int[] 语句移动到构造函数中,并将默认构造函数重写为this(3, 3) 以避免重复此代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2016-04-09
    • 2011-10-10
    相关资源
    最近更新 更多