当将输入中的值推入堆栈时,我在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);
答案 0 :(得分:0)
您已经初始化了一个Stacks数组,但是您实际上并没有分配Stacks并将其放入所说的Array中。在main()函数中,您应该执行以下操作:
for (int i = 0; i < 4; i++)
{
towersOfHanoi[i] = new Stack<Integer>();
}
编辑:在致电hanoi(n)
之前执行此操作。否则,您将在分配对象之前先引用它们。