线程中的异常无法读取构造函数中的值
线程“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]);
}
}
}
}
我无法从用户那里读取构造函数中的值
回答
首先运行字段初始值设定项,然后运行构造函数。所以,如果你打电话,说,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)以避免重复此代码。