题
尝试按索引删除节点。我想用索引打印出节点列表,以便用户可以选择索引。我认为我的逻辑可以使用索引打印列表但没有输入出来:(
在愚弄这一点时,我仍然无法打印节点列表,但是“您要删除的索引中的索引中的索引”是输出的,并且能够占用用户的选择,但最终得到了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);
}
}
.
删除方法: 公共void removeEntry(int索引){
//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--;
}
}
.
nullpointerexception来自:
//set node after temp's previous to temp's previous
temp.getNext().setPrev(temp.getPrev());
. 解决方案
You should check if temp.getNext()
is not null
before calling the setPrev()
on it.
Also, you should check with length()-1
as you have nodes which are zero indexed.
其他提示
Indices are in the range [0, length() - 1]
, so you should use
else if (index == length() - 1) {
instead.
不隶属于 StackOverflow