0

I am having some issues with my linked list class. I am currently trying to print my favorite bands in the assigned order I gave them, but I am either coming up with the program just prints null or just the band names in the wrong order. I am confused as to why or what I am missing. Any help would be appreciated.

The output I currently get is

Exception in thread "main" java.lang.NullPointerException
at project2.jacobLinkedList.toString(MetalMasher.java:171)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at project2.MetalMasher.main(MetalMasher.java:44)

The file is

import java.util.Collections;
import java.util.List;
public class MetalMasher {
    public static jacobLinkedList jacobList;
    @SuppressWarnings("unchecked")
    public static <T> void main(String[] args) {
    // this is the default constructor.
    jacobList = new jacobLinkedList();
    // add elements to the list.
    jacobList.add("MegaDeth",1993);
    jacobList.add("Slayer",1992);
    jacobList.add("Scar Symmetry",2002);
    jacobList.add("Gojira",2004);
    jacobList.add("Amon Amarth",1997);
    System.out.println("Print: jacobList:" + jacobList);
    System.out.println(".size():" + jacobList.size());
    System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
    System.out.println("Print again:" + jacobList);
    System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
    System.out.println("Print again:" + jacobList);
    System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
    System.out.println("Print again:" + jacobList);
    }
    }

class jacobLinkedList {
private static int counter;
private Node head;

// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
    head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
    jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}

private static int getCounter() {
    return counter;
}

private static void incrementCounter() {
    counter++;
}

private void decrementCounter() {
    counter--;
}

// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
    Node jacobTemp = new Node(data, i);
    Node jacobCurrent = head;

    if (jacobCurrent != null) {
        // crawl to the requested index or the last element in the list, whichever comes first
        for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
            jacobCurrent = jacobCurrent.getNext();
        }
        }

    // set the new node's next-node reference to this node's next-node reference
    jacobTemp.setNext(jacobCurrent.getNext());

    // reference to new node
    jacobCurrent.setNext(jacobTemp);

    // increment the number of elements variable
    incrementCounter();
}

// removes the element at the specified position in this list.
public boolean remove(int index) {

    // if the index is out of range, exit
    if (index < 1 || index > size())
        return false;

    Node jacobCurrent = head;
    if (head != null) {
        for (int i = 0; i < index; i++) {
            if (jacobCurrent.getNext() == null)
                return false;
            jacobCurrent = jacobCurrent.getNext();
        }
        jacobCurrent.setNext(jacobCurrent.getNext().getNext());
        decrementCounter();
        return true;
    }
    return false;
}

// returns the number of elements in this list.
public int size() {
    return getCounter();
}

public String toString() {
    String output = "";

    if (head != null) {
        Node jacobCurrent = head.getNext();
        while (jacobCurrent != null) {
            output += "[" + jacobCurrent.getData().getClass() + "]";
            jacobCurrent = jacobCurrent.getNext();
        }

    }
    return output;
}

public class Node {
    // reference to the next node in the chain
    Node next;
    Object data;
    // Node constructor
    public Node(Object dataValue, Class<Integer> class1) {
        next = (Node) null;
        data = dataValue;
    }

    // Node contructor to point towards
    @SuppressWarnings("unused")
    public Node(Object dataValue, Node ranking) {
        next = ranking;
        data = dataValue;
    }
    public Node(Object data, int i) {
        // TODO Auto-generated constructor stub
    }
    public Object getData() {
        return data;
    }

    @SuppressWarnings("unused")
    public void setData(Object dataValue) {
        data = dataValue;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node nextValue) {
        next = nextValue;
    }

    }
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 2
    What is on line # 171? – Austin Apr 27 '16 at 18:55
  • i think theres something wrong with your remove. when you say "head" do you mean the last link? if so you are setting head to the next element and setting heads "next" two linked list away .getNext().getNext() it should just be jacobCurrent.setNext(jacobCurrent.getNext()) because you already set head to the next before this statement – localplutonium Apr 27 '16 at 18:58

3 Answers3

0

From the looks of it, it's most likely the getData method in the Node object that is returning null. That's because you forgot to set the data in the constructor with an object and integer.

public Node(Object data, int i) {
        this.data = data;
    }

I don't know what the integer is for though.

Austin
  • 4,801
  • 6
  • 34
  • 54
  • the integer is suppose to be the the ranking of the band, and I was trying to print it with the assigned integer. – Jacob Reynolds Apr 27 '16 at 19:07
  • @JacobReynolds Well you don't have any integer fields in the `Node` class, so unless you relate the integer to the `Node next` field you have then it isn't doing anything. Did fixing the constructor solve your issue? – Austin Apr 27 '16 at 19:11
  • I get this now .size():0 .remove(2):false (element removed) Print again: .remove(1):false (element removed) Print again: .remove(1):false (element removed) Print again: – Jacob Reynolds Apr 27 '16 at 19:20
  • @JacobReynolds so it got rid of your error then? – Austin Apr 27 '16 at 19:26
  • it did get rid of the error however, It doesnt print the node string list. I dont know is wrong with my code and why it isn't printing however – Jacob Reynolds Apr 27 '16 at 19:28
0

in toString() method in this line:

output += "[" + jacobCurrent.getData().getClass() + "]";

You need to check when getData() returns null, which it does in most cases for your inputs.

Solution is to check for null before adding string to output. Don't know what you want with it, either add string "null" or skip such cases or fix inputs.

Adnan Isajbegovic
  • 2,227
  • 17
  • 27
0

Use:

/**
 * Created by MR on 4/27/2016.
*/
import java.util.Collections;
import java.util.List;
public class Test {
    public static jacobLinkedList jacobList;
    @SuppressWarnings("unchecked")
    public static <T> void main(String[] args) {
        // this is the default constructor.
        jacobList = new jacobLinkedList();
        // add elements to the list.
        jacobList.add("MegaDeth",1993);
        jacobList.add("Slayer",1992);
        jacobList.add("Scar Symmetry",2002);
        jacobList.add("Gojira",2004);
        jacobList.add("Amon Amarth",1997);
        System.out.println("Print: jacobList:" + jacobList);
        System.out.println(".size():" + jacobList.size());
        System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
        System.out.println("Print again:" + jacobList);
        System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
        System.out.println("Print again:" + jacobList);
        System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
        System.out.println("Print again:" + jacobList);
    }
}

class jacobLinkedList {
    private static int counter;
    private Node head;

    // Default constructor
    public jacobLinkedList() {

    }
    // appends the specified element to the end of this list.
    public void add(Object data, int i) {
    // Initialize Node only incase of 1st element
        if (head == null) {
            head = new Node(data, i);
        }
        Node jacobTemp = new Node(data, i);
        Node jacobCurrent = head;
        if (jacobCurrent != null) {
            while (jacobCurrent.getNext() != null) {
                jacobCurrent = jacobCurrent.getNext();
            }
            jacobCurrent.setNext(jacobTemp);
        }
      // increment the number of elements variable
        incrementCounter();
    }

    private static int getCounter() {
        return counter;
    }

    private static void incrementCounter() {
        counter++;
    }

    private void decrementCounter() {
        counter--;
    }

    // inserts the specified element at the specified position in this list
    public void insert(Object data, int i) {
        Node jacobTemp = new Node(data, i);
        Node jacobCurrent = head;

        if (jacobCurrent != null) {
            // crawl to the requested index or the last element in the list,           whichever comes first
            for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
                jacobCurrent = jacobCurrent.getNext();
            }
        }

        // set the new node's next-node reference to this node's next-node reference
        jacobTemp.setNext(jacobCurrent.getNext());

        // reference to new node
        jacobCurrent.setNext(jacobTemp);

        // increment the number of elements variable
        incrementCounter();
    }

    // removes the element at the specified position in this list.
    public boolean remove(int index) {

        // if the index is out of range, exit
        if (index < 1 || index > size())
            return false;

        Node jacobCurrent = head;
        if (head != null) {
            for (int i = 0; i < index; i++) {
                if (jacobCurrent.getNext() == null)
                    return false;
                jacobCurrent = jacobCurrent.getNext();
            }
            jacobCurrent.setNext(jacobCurrent.getNext().getNext());
            decrementCounter();
            return true;
        }
        return false;
    }

    // returns the number of elements in this list.
    public int size() {
        return getCounter();
    }

    public String toString() {
        String output = "";

        if (head != null) {
            Node jacobCurrent = head.getNext();
            while (jacobCurrent.getData() != null) {
                output += "[" + jacobCurrent.getData().getClass() + "]";
                jacobCurrent = jacobCurrent.getNext();
            }

        }
        return output;
    }

    public class Node {
        // reference to the next node in the chain
        Node next;
        Object data;
        // Node constructor
        public Node(Object dataValue, Class<Integer> class1) {
            next = (Node) null;
            data = dataValue;
        }

        // Node contructor to point towards
        @SuppressWarnings("unused")
        public Node(Object dataValue, Node ranking) {
            next = ranking;
            data = dataValue;
        }
        public Node(Object data, int i) {
            // TODO Auto-generated constructor stub
        }
        public Object getData() {
            return data;
        }

        @SuppressWarnings("unused")
        public void setData(Object dataValue) {
            data = dataValue;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node nextValue) {
            next = nextValue;
        }

    }
}

I hope this helps you

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27