通过调用方法初始化数组

initializing an array by calling a method

我用 java 编写了这个程序,但我在运行时遇到了困难。

public static void main(String[] args) {
33. int[][] maze_matrix = input();
    int check = inputCheck(maze_matrix);
    if(check==1){
        startApplication(maze_matrix);
    }
    else{
        System.out.println("Source and destination entered is not valid.");
    }
}

input()方法如下:

 138.private static int[][] input() {


    System.out.println("Enter the size of the maze row_by_column");
    n = in.nextInt(); //Entering rows.
    m = in.nextInt(); //Entering columns.

    int ar_maze[][]= new int[n][m];
    //Initializing the array with given rows and columns.

    for (int i=0;i<n;i++) {
        for(int j=0;j<m;j++) {
152.    ar_maze[i][j] = rand.nextInt(2);
    }

     //Filling array randomly with 0's and 1's.
    return ar_maze;

161.    }

我得到一个:

Exception in thread "main" java.lang.NullPointerException
at MazeApplication.input(MazeApplication.java:152)
at MazeApplication.main(MazeApplication.java:33)

数组不能这样初始化吗?如果不是,为什么?

您没有提供完整的代码示例,但看起来 rand 可能为空。

您可以这样做:

Random rand = new Random();

或者,在输入函数的顶部:

private static int[][] input() {
    if(rand == null) // initialize Random for the first time
        rand = new Random();

    ...
}

好像不是数组的问题,请问rand是在哪里初始化的? 你应该这样做:

Random rand = new Random(); 

for 循环之前

at MazeApplication.input(MazeApplication.java:152) 此时唯一可能的空指针是rand.

你应该在 input() 的开头像这样初始化你的兰特 Random rand = new Random();;