有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中试图打印数组时出现NullPointerException

问题是,我试图打印之前在构造函数中创建的矩阵,但它似乎是空的

以下是构造函数的代码:

public Matrix(int row_col){
    int [][] randomMatrix = new int[row_col][row_col];
    Random rand = new Random();
    if (row_col > 0 && row_col < ROW_LIMIT && row_col < COL_LIMIT)
    for (int i = 0; i < randomMatrix.length; i++) 
     for (int j = 0; j < randomMatrix[0].length; j++)
         randomMatrix[i][j] = rand.nextInt(51);
}

以及打印方法的代码:

public void print(){
    int row = randomMatrix.length;
    int col = randomMatrix[0].length;
    for(int i=0 ; i < row ; i++)
     for(int j=0 ; j < col ; j++)
        System.out.print(randomMatrix[i][j]);
}

你好


共 (1) 个答案

  1. # 1 楼答案

    看起来randomMatrix是直接在构造函数的作用域中定义的,而不是存储在类的字段中

    如果已经有一个randomMatrix作为字段,请删除构造函数方法第一行中的int[]],以便引用该字段,而不是声明新变量