0

im readin from a file in main and in main i store ticks as a variable then i pass it to linkedList.insertNode() then it goes to the Node class and the values are set and when i call the linkedList.printAll(); from main i get a NULLPOINTEREXCEPTION and i dont understand why. Am i not printing ticks value? List Snippet

class List{
 private Node ptr;
 private int ticks;
 private int jobId;
 private String name;

public List(){
 ptr = null;
 }

 public void insertNode(int t,int j, String name){

   Node node = new Node(t,j,name);
   if(ptr == null){
     node.next = node;
     node.prev = node;

   }//end if
public void printAll(){
   System.out.format("%d",ptr.getTicks());

 }

Node Spippet

class Node{
  private int ticks;
  private int jobId;
  private String name;
  Node next;
  Node prev;

  public Node(int t,int j, String name){
    this.ticks = t;
    this.jobId = j;
    this.name = name;
    setNext(null);
  }

MAIN(snippet)

  linkedList.insertNode(ticks,jobId,name);
     linkedList.printAll();
cmehmen
  • 249
  • 1
  • 3
  • 12

2 Answers2

1

ptr is never assigned, so it remains null.

Therefore System.out.format("%d",ptr.getTicks()); throws NullPointerException.

Your insertNode code makes no sense. You create a new Node which points to itself, and is never connected to the list.

It should probably be something like :

 public void insertNode(int t,int j, String name){  
   Node node = new Node(t,j,name);
   if(ptr == null){
       ptr = node;
   } else {
     node.next = ptr;
     ptr.prev = node;
     ptr = node;
   }
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You aren't assigining anything in ptr. i think you need to do this

   if(ptr == null){
         ptr = node;
   }else {
        //append this node to the ptr
        node.next = ptr; 
        ptr.prev = node;
        ptr = node;
   }
shikjohari
  • 2,278
  • 11
  • 23