单元测试时出现NullPointerException错误

时间:2020-10-11 09:19:15

标签: java nullpointerexception stack nodes

当我对pop类的peekMyStack方法进行单元测试时,遇到了与节点类的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;
    }
}

1 个答案:

答案 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,因此我不会在此答案中详述。


我强烈建议您研究如何使用调试器来逐步执行代码。因此,您可以逐行执行程序,并查看程序与预期的偏离之处。调试是程序员必不可少的技能。这是三个资源: