Trying to remove a node by index now. I'd like to print out the list of nodes with indices so the user can select the index as seen. I think my logic is okay in printing the list with the indices but no input is coming out :(
At one point in fooling around with this, I was still unable to print the list of nodes but the "enter in the index you wish to delete" was output and was able to take a users' selection but eventually got a NullPointerException.
else if (menu.equals("d")) {
EntryNode temp = head;
while (temp != null) {
for (int i = 0; i < addressBook.length(); i++) {
//gets node at index
System.out.println(temp.getFirstName() + i);
temp = temp.getNext();
}
System.out.println(" ");
System.out.println("Please enter the index of the entry you wish to delete ");
int index = keyboard.nextInt();
addressBook.removeEntry(index);
}
}
The removal method: public void removeEntry(int index){
//delete from the head
if (index == 0) {
EntryNode temp = head;
head = temp.getNext();
temp.setNext(null);
head.setPrev(null);
size--;
}
//delete from the tail
else if (index == length()) {
EntryNode temp = tail;
temp.setPrev(null);
tail.setNext(null);
tail = temp.getPrev();
size--;
}
//in the middle
else {
EntryNode temp = head;
for (int i = 0; i < index; i++) {
//gets node at index
temp = temp.getNext();
}
//set node after temp's previous to temp's previous
temp.getNext().setPrev(temp.getPrev());
temp.getPrev().setNext(temp.getNext());
temp.setNext(null);
temp.setPrev(null);
size--;
}
}
The NullPointerException comes from :
//set node after temp's previous to temp's previous
temp.getNext().setPrev(temp.getPrev());
else if (index == length()) {beelse if (index == length() -1 ) {instead? If you start indexing from 0 andlength()is the number of elements, the index of the tail will belength() - 1and notlength().