在pop方法上获取NullPointerException

时间:2013-04-22 05:14:48

标签: java

我从Linked Stacks开始,我想知道为什么这部分代码会给我一个NullPointerException。我想在主驱动程序中做的一件事是继续添加书籍,直到我在提示时输入停止。 push方法似乎正在工作,因为在输出列表的顶部你可以看到Book-2在顶部。我试图以其他方式接近它,但它一直给我那个确切的错误。 注意我已经读过我写这篇文章时出现的类似问题,但我似乎无法找到问题。

以下是推送和弹出的代码:

@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)

1 个答案:

答案 0 :(得分:0)

问题是你检查top是否为null,但是不是通过返回来停止方法,而是打印一个警告并继续进行,好像它不是null。几行后,您访问该数组,如果它为null,则为kaboom。

尝试这样的事情:

 if(count == 0 || top == null )
 {
     System.out.println("List is empty");
     return null; // ADDED THIS LINE!
 }

修改

即使top不为null,如果将null添加到列表中,您也会被清除:

top[count].getData()

如果top[count]中存有空值,则会抛出NPE。