队列中的Java空指针异常
我一直在尝试编写一个使用节点文件的队列,但我似乎不知道空指针异常在哪里是一个问题。我在网上看了一下,但我对Java太陌生了,我想我不明白我在这里要找什么。有人能找到它吗,或者至少能把我引向正确的方向 首先是队列:队列中的Java空指针异常,java,exception,pointers,null,queue,Java,Exception,Pointers,Null,Queue,我一直在尝试编写一个使用节点文件的队列,但我似乎不知道空指针异常在哪里是一个问题。我在网上看了一下,但我对Java太陌生了,我想我不明白我在这里要找什么。有人能找到它吗,或者至少能把我引向正确的方向 首先是队列: public class Queue extends CharNode { public CharNode head; public CharNode tail; public Queue(){ this.head = null; this.tail = null;}
public class Queue extends CharNode {
public CharNode head;
public CharNode tail;
public Queue(){
this.head = null;
this.tail = null;}
public boolean isEmpty(){
return (head==null);}
public void enqueue(Character character){
if (isEmpty()){
head.character = character;
head.nextNode = tail;}
else {
CharNode oldTail = tail;
tail = new CharNode();
oldTail.character = character;
oldTail.nextNode = tail;
}
}
public Character dequeue(){
if (isEmpty()) throw new RuntimeException("Queue Empty");
head.character = character;
head = head.nextNode;
return character;
}
public static void main(String[] args){
Queue queue = new Queue();
queue.enqueue('a');
queue.enqueue('b');
System.out.print(queue.dequeue());
}
}
我的CharNode文件如下所示:
public class CharNode {
public Character character;
public CharNode nextNode;
public void charNode(Character character){
this.character = character;
this.nextNode = null;
}
Exception in thread "main" java.lang.NullPointerException
at Queue.enqueue(Queue.java:14)
at Queue.main(Queue.java:32)
}
我收到的例外情况如下:
public class CharNode {
public Character character;
public CharNode nextNode;
public void charNode(Character character){
this.character = character;
this.nextNode = null;
}
Exception in thread "main" java.lang.NullPointerException
at Queue.enqueue(Queue.java:14)
at Queue.main(Queue.java:32)
可能有效的是
if (isEmpty()){
head = new CharNode (); // There is no Constructor for CharNode (Character)
head.character = character;
如果head为null,则isEmpty返回true。您尝试在enqueue方法中使用null对象的值,这会导致NPE。 这一行:
head.character=字符 首先,队列不应该扩展CharNode;那里没有关系,当然。谢谢。这一定是我第一次看到if object==null//形式的空检查。用那个对象做点什么。你必须过一种有庇护的生活;-很多时候,也许是一个好消息!我很困惑,我只想在队列为空时分配头,这样我就可以在没有迭代器的情况下保持FIFO。这不是用头为空值来表示吗?我这里没有得到什么?在分配给它之前,您需要实例化一个新的head CharNode。