当我对pop
类的peek
和MyStack
方法进行单元测试时,遇到了与节点类的NullPointerException
方法有关的getData
我无法说出原因,我想知道是否有人对如何解决它和使它变得没有NullPointerException
有任何想法。我尝试编辑节点的工作方式以及getData
本身的工作方式,但是找不到解决方案,并且由于无法解决问题。任何帮助将不胜感激
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
public Node<E> head;
public int nodeCount = 0;
public static void main(String args[]) {
}
public E peek() {
return head.getData();
}
public E pop() {
if (nodeCount == 0) {
throw new EmptyStackException();
}
E item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head == null && nodeCount == 0) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
int count = 0;
Node<E> current = new Node<E>(head.getData());
while (current.getData() != o) {
current.getNext();
count++;
}
return count;
}
}
public class Node<E>
{
public E data;
public Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return this.data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
答案 0 :(得分:0)
您的push
方法存在一个问题。在那里,您没有将新的 head 分配给在类级别定义的成员变量。更新后的push
方法如下所示:
public void push(E data) {
Node<E> newHead = new Node<>(data);
newHead.setNext(head);
head = newHead;
nodeCount++;
}
在peek
中,您应先检查堆栈是否为空,然后再尝试访问getData()
:
public E peek() {
if (empty()) {
throw new EmptyStackException();
}
return head.getData();
}
另一种NullPointerException
发生在search
方法中,其中head.getData()
是null
表示一个空堆栈。此外,此方法不会报告项目在堆栈上的正确位置。由于您已经问过separate question,因此我不会在此答案中详述。
我强烈建议您研究如何使用调试器来逐步执行代码。因此,您可以逐行执行程序,并查看程序与预期的偏离之处。调试是程序员必不可少的技能。这是三个资源: