gpt4 book ai didi

java - 通过调用方法初始化数组

转载 作者:行者123 更新时间:2023-12-01 07:22:23 25 4
gpt4 key购买 nike

我用 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)

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

最佳答案

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

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

关于java - 通过调用方法初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32588687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com