daw*_*h77 -1 java queue null pointers exception
我一直在尝试编写一个使用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());
}
Run Code Online (Sandbox Code Playgroud)
}
我的CharNode文件如下所示:
public class CharNode {
public Character character;
public CharNode nextNode;
public void charNode(Character character){
this.character = character;
this.nextNode = null;
}
Run Code Online (Sandbox Code Playgroud)
}
我收到的例外情况如下:
Exception in thread "main" java.lang.NullPointerException
at Queue.enqueue(Queue.java:14)
at Queue.main(Queue.java:32)
Run Code Online (Sandbox Code Playgroud)
public boolean isEmpty(){
return (head==null);}
public void enqueue(Character character){
if (isEmpty()){
head.character = character; // you have just said that head is NULL
Run Code Online (Sandbox Code Playgroud)
可能有用的是什么
if (isEmpty()){
head = new CharNode (); // There is no Constructor for CharNode (Character)
head.character = character;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1927 次 |
| 最近记录: |