-1

So I implemented a queue in Java and I was Trying to implement a procedure that inserts an element at the end of the queue.But I get an error message "java.lang.NullPointerException".I am new at this and I don't know what this means or how to fix it.

class Node {

public int ielement;
public String selement;
public Node next;




public Node(int iel, String sel) {

    ielement = iel;
    selement = sel;
}
class Implement {


private Node head;
private Node tail;

 public Implement() {
    head = null;
    tail=null;
}
public void InsertAtTheEnd(int iel, String sel){
    Node newNode=new Node(iel,sel);
    if(!Empty())//if the queue is empty{
    tail.next=newNode;
    tail=newNode;}
    else{
    newNode.next=head;
    head=newNode;
        }

}

   public static void main(String[] args) {

   Implement k = new Implement();
   k.InsertAtTheEnd(1, "b");
   k.InsertAtTheEnd(3, "bes");
   k.InsertAtTheEnd(4, "kes");}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
jstack
  • 11
  • 7

1 Answers1

0

You never initialize tail. If the queue is not empty, tail.next should point to the newly created node, as you have done. If it is, though, both head and tail should just point to the newly added node.

public void insertAtTheEnd (int iel, String sel) {
    Node newNode = new Node(iel,sel);
    if (!empty()) {
        tail.next = newNode;
        tail = newNode;
    } else {
        head = newNode;
        tail = newNode;
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350