首页 > 解决方案 > 我怎么会得到一个空指针异常

问题描述

将输入中的值推入堆栈时,我在 hanoi 函数中收到 NullPointerException,我不确定为什么这是我的代码:

public class Hanoi {

public static Stack<Integer>[] towersOfHanoi = new Stack[4];
static int moves;

public static void hanoi(int n) {

    for(int i = n; n > 0; i--) {
        towersOfHanoi[1].push(i);
    }

    moveDisc(n, 1, 2, 3);
}

public static void moveDisc(int n, int j, int k, int l) {

    moveDisc(n-1, j, k, l);
    int i = towersOfHanoi[j].pop();
    towersOfHanoi[k].push(i);
    moves++;
    moveDisc(n-1, l, j, k);
}

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);

    System.out.println("Enter number of discs: ");
    int n = in.nextInt();
    in.close();

    hanoi(n);

    towersOfHanoi[1] = new Stack<Integer>();
    towersOfHanoi[2] = new Stack<Integer>();
    towersOfHanoi[3] = new Stack<Integer>();

    System.out.println(moves);

标签: javastack

解决方案


您已经初始化了一个 Stacks 数组,但实际上并没有分配 Stacks 并将它们放入所述数组中。在您的 main() 函数中,您应该执行以下操作:

for (int i = 0; i < 4; i++)
{
  towersOfHanoi[i] = new Stack<Integer>();
}

编辑:在你打电话之前做这个hanoi(n)。否则,您将在分配对象之前引用它们。


推荐阅读