-3

我从链接堆栈开始,我想知道为什么这部分代码给了我一个 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)
4

1 回答 1

0

问题是您检查是否为top空,但不是通过返回来停止该方法,而是打印一个警告并继续执行,就好像它不为空一样。几行之后,您访问数组,如果它是 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 。

于 2013-04-22T05:24:30.140 回答