0

I am trying to add a node to the end of my linked-list, but everytime I run the program I keep getting an error of a null pointer.

 public class Names {

        public String name;
        public Names next, prev;

        public Names(String name, Names next)
        {
            this.name = name;
            this.next = next;
        }

        public Names(String name)
        {
            this.name = name;
        }

        public static void addName(Names newName, Names list)
        {
            Names current = list;

            while (current != null)
            {
                current.prev = current;
                current = current.next;
            }


            current.next = newName;
        }

        public static void removeName(String toDelName, Names list)
        {
            Names current = list;

            while (current != null)
            {
                current.prev = current;
                current = current.next;
                if (current.name == toDelName)
                {
                    current.prev.next = current.next;
                    current.next.prev = current.prev;
                }
            }


        }

        public static void printNames(Names list)
        {
            System.out.print("Names: ");
            while (list != null)
            {
                System.out.print(list.name + " ");
                list = list.next;
            }

        }


        public static void main(String[] args)
        {

            Names ListOfNames = new Names("Jason", new Names("Jim", new Names("Ray", null)));

            Names name1 = new Names("Rick"), name2 = new Names("Chad", name1);

            printNames(ListOfNames);

            addName(name1, ListOfNames);
            System.out.println();

            printNames(head);
        }

    }

This is where it is occuring.

  Exception in thread "main" java.lang.NullPointerException at    Names.addName(Names.java:34)

It is a result of `current.next = newName`
Rustam
  • 6,485
  • 1
  • 25
  • 25
Chrismar
  • 93
  • 1
  • 9
  • 3
    Look at the loop just above that statement - it will *only* get out of the loop when `current` is null, so what did you expect `current.next = newName` to do? – Jon Skeet Sep 17 '15 at 09:43
  • just add a line `current=list;` before `current.next = newName` – Rustam Sep 17 '15 at 09:47
  • You have iterated till current is null, and now you are trying to access current.next. Here is the problem. You need to do something like public static void addName(Names newName, Names list) { Names current = list; while (current.next != null) { current.prev = current; current = current.next; } current.next = newName; } Then you will not get null pointer exception. – Kuldeep Singh Sep 17 '15 at 09:57

0 Answers0