如何解决在空指针处停止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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。