我从链接堆栈开始,我想知道为什么这部分代码给了我一个 NullPointerException。我想在主驱动程序中做的一件事是继续添加书籍,直到出现提示时输入停止。push 方法似乎有效,因为在输出列表的顶部,您可以看到 Book - 2 位于顶部。我试图以其他方式接近它,但它一直给我那个确切的错误。注意我已经阅读了写这篇文章时出现的类似问题,但我似乎找不到问题所在。
这是 push 和 pop 的代码:
@Override
public void push(T data)
{
Node<T> current = new Node<>(data, top);
if(count == top.length)
{
expandCapacity();
}
current.setNext(top);
top[count++] = current;
}
这是我遇到问题弹出方法的地方
@覆盖
public T pop()
{
T result;
if(count == 0 || top == null )
{
System.out.println("List is empty");
}
result = top[count].getData();
top = top[count - 1].getNext();
return result;
}
这是 LinkedStack 的声明和构造函数
public class LinkedStack<T> implements linkedInterface<T> {
private int count;
private Node<T> []top;
private static final int size = 5;
public LinkedStack()
{
top = (Node<T>[]) (new Node [size]);
count = 0;
}
这是Node类的代码
public class Node<T>
{
private T data;
private Node []next;
public Node(T _data)
{
data = _data;
}
public Node(T _data, Node []_next)
{
data = _data;
next = _next;
}
public T getData()
{
return data;
}
public void setData(T _data)
{
data = _data;
}
public Node[] getNext()
{
return next;
}
public void setNext(Node []_next)
{
next = _next;
}
}
输出
Note to stop adding books enter: 'stop' when prompted.
Book-1
Enter title:
title1
author1
ISBN1
10
Do you wish stop adding books? N || stop
n
Book-2
Enter title:
title2
author2
ISBN2
20
Do you wish stop adding books? N || stop
stop
The books in list are:
Title:title2
Author/s: author2
ISBN: ISBN2
Exception in thread "main" java.lang.NullPointerException
Copies in stock: 20
at node.LinkedStack.pop(LinkedStack.java:133)
at node.BookDriver.main(BookDriver.java:85)
Java Result: 1
BUILD SUCCESSFUL (total time: 36 seconds)