队列中的Java空指针异常

时间:2013-10-21 05:28:19

标签: java exception pointers null queue

我一直在尝试编写一个使用Node文件的队列,我似乎无法弄清楚空指针异常的问题所在。我在网上看了一下,但我对Java太新了,我想要理解我在这里寻找的东西。任何人都可以找到它或者至少引导我朝着正确的方向前进吗?

首先是队列:

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)

2 个答案:

答案 0 :(得分:5)

public boolean isEmpty(){
    return (head==null);}

public void enqueue(Character character){
    if (isEmpty()){
        head.character = character;   // you have just said that head is NULL

可能有用的是

if (isEmpty()){
        head = new CharNode ();     // There is no Constructor for CharNode (Character)
        head.character = character;

答案 1 :(得分:0)

如果head为null,则

isEmpty()返回true。并且您尝试在enqueue方法()中使用null对象的值,这会导致NPE。 这一行: head.character = character;