尝试打印链表的项目时获取空指针

时间:2019-03-10 18:57:58

标签: java linked-list singly-linked-list

基本上,我试图在我写的称为BirdSurvey的链表类中打印每种特定类型的鸟的数量。但是,当我尝试使用printList方法打印项目时,出现了一个空指针异常:Exception in thread "main" java.lang.NullPointerException at BirdSurvey.printList(BirdSurvey.java:39)。我进行了调试,并认为这与我的节点无法在列表中找到下一个项目有关在我的if语句中。是的,手工写一个链表是我的家庭作业,但是我已经走了这么远,所以我希望有人能告诉我为什么我会遇到这种情况。 鸟类课程:

    class Birds
{
    String birdType;
    Birds(String birdType)
    {
        this.birdType = birdType;
    }
    public String getBirdType()
    {
        return birdType;
    }
}

鸟类的链接列表类:

class BirdSurvey
{
    static Node head;

    static class Node{
        Birds data;
        Node next;
        int count;
        Node()
        {

        }
        Node(Birds x)
        {
            data = x;
            next =null;
            count =0;
        }

    }
    public void printList()
    {
        Node _node = head;
        while(_node != null)
        {
            if (_node.data.getBirdType().equals(_node.next.data.getBirdType()))
            {
                //increase count if bird species has been seen in list before
                _node.count+=1;
            }
            _node=_node.next;
        }
        while(_node != null)
        {
            //print out the birds and number of times they were in the list
            System.out.print("Bird Type:"+_node.data.getBirdType()+" "+ "Count: ");
            _node=_node.next;
        }
    }
public static void main(String[] args)
    {
        BirdSurvey _list = new BirdSurvey();

        _list.head = new Node(new Birds("blue jay"));
        Node second = new Node(new Birds("orange jay"));
        Node third = new Node(new Birds("orange jay"));


        _list.head.next=second;
        second.next=third;

        _list.printList();
    }
}

0 个答案:

没有答案