在空指针处停止While循环

问题描述

我必须在Java程序中使用do while循环作为其显示方法,但运行时会出现Null Exception错误。我不知道如何将其合并为不等于null 该程序一直运行到到达空队列为止。

Node<T> currNode = lastNode.next;

System.out.println("The queue elements are: " );
do{
    System.out.print(currNode.data + " ");
    currNode = currNode.next;

}while(currNode != lastNode.next);

System.out.println();

这是我上面的代码,也许这里有问题?

public class CircularLinkedQueue<T> implements QueueInterface<T> {
    private Node<T> lastNode; // References node for back of queue


    public CircularLinkedQueue() {
        this.lastNode = null;
    } // end default constructor

    public void enqueue(T newEntry) {

        // TODO Project 2A
        Node newNode = new Node(newEntry);
        if (lastNode != null) {
            newNode.next = lastNode.next;
            lastNode.next = newNode;
        } else
            newNode.next = newNode;
        lastNode = newNode;

    } // end enqueue

    public T dequeue() throws EmptyQueueException {

        // TODO Project 2A

        T front = null;
        if (!isEmpty()) {
            if (lastNode.data.equals(lastNode.next.data)) {
                front = lastNode.data;
                this.lastNode = null;
            } else {
                front = lastNode.next.data;
                lastNode.next.data = lastNode.next.next.data;
                lastNode.next.next = lastNode.next.next.next;
            }

        }
        return front; // THIS IS A STUB
    } // end dequeue

    public T getFront() throws EmptyQueueException {
        // TODO Project 2A
        T front;

        if (!isEmpty()) {
            front = lastNode.next.data;
            return front;
        }

        throw new EmptyQueueException();

        // THIS IS A STUB
    } // end getFront

    public boolean isEmpty() {
        return this.lastNode == null;
    } // end isEmpty

    public void clear() {
        this.lastNode = null;
    } // end clear

解决方法

如果要编写一个遍历所有迭代器元素的while循环,则应执行以下操作:

Node<T> currNode = lastNode.next;
System.out.println("The queue elements are: " );
while(currNode != null) {
     System.out.print(currNode.data + " ");
     currNode = lastNode.next;
}
System.out.println();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...