在java中调用函数时出现NullPointerException

时间:2014-04-30 04:43:32

标签: java nullpointerexception

我已经编写了以下代码来查找迷宫问题中老鼠的可能路径数,但是它显示了第23行和第29行的粗体显示的NullPointer异常。请帮忙。

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;
    }
}

1 个答案:

答案 0 :(得分:4)

您的二维数组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);
}