0

I am trying to make it dequeue the front node and print it out, however I am getting the following error:

Exception in thread "main" java.lang.NullPointerException
at MyQueue.toString(MyQueue.java:25)
at TestQueue.main(TestQueue.java:13)

From the TestQueue class, I am expecting the outputs 1 then after dequeueing 1 again, then finally 2 from the second toString call.

public class TestQueue {

public static void main(String[] args) {
    MyQueue<String> qStr = new MyQueue();
    qStr.enqueue("1");
    qStr.enqueue("2");
    qStr.enqueue("3");
    qStr.enqueue("4");
    qStr.enqueue("5");
    qStr.toString(qStr.front);
    qStr.dequeue();
    qStr.toString(qStr.front);



}

}  


public class MyQueue<T>{
MyNode<T> back;
MyNode<T> front;

public MyQueue(){
    back = null;
    front = null;

}
public void enqueue(T payload) {
    if(back == null) {
    MyNode<T> firstnode = new MyNode<T>(payload);
    back = firstnode; 
    front = firstnode;
}
else {
    MyNode<T> addtoback = new MyNode<T>(payload, back.next, null);
    back = addtoback;



 }
}
public String toString(MyNode<T> x) {
System.out.println(x.payload);

if(x.payload == null) {
    return "";
    }
    else{
        return (String) x.payload;
    }
}
public void dequeue() {
if (isEmpty()) {
    throw new RuntimeException("Queue underflow");
} else if (front == back) {
    T payload1 = front.payload;
    front = null;
    back = null;
    System.out.println(payload1);
}

T payload1 = front.payload;
front = front.previous;
System.out.println(payload1);

}

public Boolean isEmpty() {
if(back==null) {
    return true;
}
return false;
}

public int size() {
MyNode<T> k = back;
if(isEmpty()||k.next==null) {
    return 0;
}
k = k.next;
return 1+size();
}
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
halo2x2
  • 33
  • 1
  • 7
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zachary Feb 18 '18 at 01:32

1 Answers1

0

You never set the previous variable in the MyNode class.

What is happening is that you set the front variable in the MyQueue class when you call enqueue(T) for the first time. Once you call dequeue() for the first time it sets the front variable in the MyQueue to the previous variable in the MyNode class which is never set. front in the MyQueue class becomes null and the next time toString(MyNode<T>) is called you get a NullPointerException.

That is also why the first call to toString(MyNode<T>) doesn't give a NullPointerException. dequeue() wasn't called yet.

Julian
  • 837
  • 1
  • 11
  • 24