ContactList.java:
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ContactNode headNode = new ContactNode();
ContactNode traverse = new ContactNode();
String name;
String phoneNum;
String newLineEater;
for (int i = 1; i < 4; i++){
System.out.println("Person " + i);
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
phoneNum = scnr.nextLine();
ContactNode newNode = new ContactNode(name, phoneNum);
System.out.println("You entered: " + name + ", " + phoneNum);
System.out.println();
newNode.insertAfter(headNode);
/* Type your code here. */
}
System.out.println("CONTACT LIST");
traverse = headNode.getNext();
traverse.printContactNode();
}
}
And then:
public class ContactNode{
private String contactName;
private String contactPhoneNumber;
private ContactNode nextNodePtr;
public ContactNode(){
contactName = "n/a";
contactPhoneNumber = "no phone number";
}
public ContactNode(String contactName, String contactPhoneNumber){
this.contactName = contactName;
this.contactPhoneNumber = contactPhoneNumber;
}
public String getName(){
return contactName;
}
public String getPhoneNumber(){
return contactPhoneNumber;
}
public void printContactNode(){
System.out.println("Name: " + this.contactName);
}
public ContactNode insertAfter(ContactNode prevNode){
return this.nextNodePtr = prevNode;
}
public ContactNode getNext(){
return this.nextNodePtr;
}
}
The two class files are posted above. The error is: Exception in thread "main" java.lang.NullPointerException at ContactList.main(ContactList.java:37)
I thought that I could just reference the Node to test if it had pointed to something. It doesn't. Why? I understand that it NEEDS to point to something, but when I created the Nodes, I thought I had linked them together? What am I missing?
I'm trying to understand the fundamentals of linked lists, and any responses would be super helpful. Thank you!