1

I have a problem while I'm trying to put an array of Strings on the Node of the LinkedList and this is the code which I have used.

public class Node { 

    public Node next ; 
    public String[] data;

    public Node (Node next ) {
        this.next = next ;
        this.data = new String[6];
    }
}

This is the add function to add the array inside the Node of the LinkedList:

public void add() {
    Node current = head;
    if (head == null) {
        for (int i = 0; i < 6; i++) {
            head.data[i] = numData[i];
        }
    } else
        while (current != null) {
            current = current.next;
        }

    for (int i = 0; i < 6; i++) {
        current.data[i] = numData[i];
    }
}

Error: Exception in thread "main" java.lang.NullPointerException

deHaar
  • 17,687
  • 10
  • 38
  • 51

2 Answers2

0

need to change logic

Node current = head ; 
       if(head == null ){
       for(int i = 0 ; i<6 ; i++){
       head.data[i] = numData[i] ;  //here you will get npe beacuse you are using null reference  of head
          }
       }
       else 
       while(current != null){
       current = current.next ; 
       }
       for(int i = 0 ; i<6 ; i++){
           current.data[i] = numData[i] ;//here you will get npe beacuse you are using null reference  of current
            }
       }
0

In your add method, current is null in the last for loop and apparently if head be null you would have problems too. It seems you forgot to initiate new instances when you want to add a new node. change your method as below:

    public void add()
    {
       Node current = head ; 
       if(head == null ){
           head = new Node(null); //here you need to initiate head
           for(int i = 0 ; i<6 ; i++){
               head.data[i] = numData[i] ; 
           }
       }
       else {
           while(current.next != null){
           current = current.next ; 
           }
           Node newNode = new Node(null); //initiating a new node
           for(int i = 0 ; i<6 ; i++){
               newNode.data[i] = numData[i] ;
           }
           current.next = newNode;
       }
    }   

I just assumed you want to put data in a new node. If you want to add data to the last existing node, just change the last part of the method.

Hamid Ghasemi
  • 880
  • 3
  • 13
  • 32