I have been trying to write a queue that uses a Node file, and I can't seem to figure out where the null pointer exception is an issue. I looked online a bit but I'm too new to Java I think to understand what I'm looking for here. Can anyone find it or at least lead me in the right direction??
我一直在尝试编写一个使用Node文件的队列,我似乎无法弄清楚空指针异常的问题。我在网上看了一下,但我对Java太新了,我想要理解我在这里寻找的东西。任何人都可以找到它或者至少引导我朝着正确的方向前进吗?
First the Queue:
首先是队列:
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());
}
}
My CharNode file looks like:
我的CharNode文件如下所示:
public class CharNode {
public Character character;
public CharNode nextNode;
public void charNode(Character character){
this.character = character;
this.nextNode = null;
}
}
And the exception I received looks like:
我收到的例外情况如下:
Exception in thread "main" java.lang.NullPointerException
at Queue.enqueue(Queue.java:14)
at Queue.main(Queue.java:32)
2 个解决方案
#1
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
What may work is
可能有用的是什么
if (isEmpty()){
head = new CharNode (); // There is no Constructor for CharNode (Character)
head.character = character;
#2
0
isEmpty() returns true if head is null. And you try to use a null object's value at enqueue method() which causes NPE. This line: head.character = character;
如果head为null,则isEmpty()返回true。并且您尝试在enqueue方法()中使用null对象的值,这会导致NPE。这一行:head.character = character;
#1
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
What may work is
可能有用的是什么
if (isEmpty()){
head = new CharNode (); // There is no Constructor for CharNode (Character)
head.character = character;
#2
0
isEmpty() returns true if head is null. And you try to use a null object's value at enqueue method() which causes NPE. This line: head.character = character;
如果head为null,则isEmpty()返回true。并且您尝试在enqueue方法()中使用null对象的值,这会导致NPE。这一行:head.character = character;