java - 我怎么会得到一个空指针异常
问题描述
将输入中的值推入堆栈时,我在 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);
解决方案
您已经初始化了一个 Stacks 数组,但实际上并没有分配 Stacks 并将它们放入所述数组中。在您的 main() 函数中,您应该执行以下操作:
for (int i = 0; i < 4; i++)
{
towersOfHanoi[i] = new Stack<Integer>();
}
编辑:在你打电话之前做这个hanoi(n)
。否则,您将在分配对象之前引用它们。
推荐阅读
- java - 从java到golang对话的AESBase64加密解密
- shell - 在 bash -c 中读取命令行 ENV
- node.js - 资源依赖于另一个的架构问题
- c# - 在 C# 中的水晶报表中传递参数不起作用
- reactjs - 如何使用 React js 打开动态模式
- java - 事务 - 发生意外回滚 - 无法理解
- flutter - TabBar 阻碍 AppBar 主体
- javascript - 使用 if/else 语句 (JavaScript) 登录后如何重定向用户?
- haproxy - 将 haproxy 从 url 重定向到另一个保持相同的路径/uri
- python-3.x - 使用带有来自标记的参数的 pytest 夹具