gpt4 book ai didi

java - 在java中调用函数时出现NullPointerException

转载 作者:行者123 更新时间:2023-12-01 18:32:46 24 4
gpt4 key购买 nike

我编写了以下代码,用于查找迷宫问题中老鼠的可能路径数量,但它在第 23 行和第 29 行以粗体显示了 NullPointer Exception。请帮忙。

import java.util.*;
import java.io.*;
public class rat_in_a_maze

{

static int n;
static int[][] a;
static int path;

public static void main(String[] ar) throws IOException
{
n=7;
int a[][]={ {0,0,1,0,0,1,0},
{1,0,1,1,0,0,0},
{0,0,0,0,1,0,1},
{1,0,1,0,0,0,0},
{1,0,1,1,0,1,0},
{1,0,0,0,0,1,0},
{1,1,1,1,0,0,0}};

search(0,0); //NPE here
System.out.println(path);
}

public static void search(int i, int j)
{
if(!exist(i,j) || a[i][j] == 1) // NPE here
return;
if(i == n-1 && j == n-1)
{
path++;
return;
}
a[i][j] = 1;
search(i+1,j);
search(i-1,j);
search(i,j+1);
search(i,j-1);
a[i][j] = 0;
}

public static boolean exist(int i, int j)
{
return i>=0 && j >=0 && i < n && j < n;
}
}

最佳答案

您的二维数组a为空。您的目的是在 main() 方法内初始化它,但您声明了新的本地数组,而不是初始化全局静态数组 a
你的代码应该是这样的:

public static void main(String[] ar) throws IOException {
n=7;
a = new int[][]{ {0,0,1,0,0,1,0},
{1,0,1,1,0,0,0},
{0,0,0,0,1,0,1},
{1,0,1,0,0,0,0},
{1,0,1,1,0,1,0},
{1,0,0,0,0,1,0},
{1,1,1,1,0,0,0}};

search(0,0);
System.out.println(path);
}

关于java - 在java中调用函数时出现NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23379825/

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