問題描述
Kesalahan NullPointerException dalam kode Java saya. (NullPointerException errors in my Java code.)
Do you guys see anything wrong with my code off the top of your head:
/** simulates the Josephus game by killing every other person
until the winner is the only one left.
@return The survivor of the game
*/
public E startJosephus() {
E item =head.data;
if(head.next != null){
if(head == head.previous)
return item;
}
else{
while(count>1){
removeAfter(head);
head =head.next;
}
}
return item;
}
Here is my full code: http://pastebin.com/S0kWwFFV
Here is my driver class as well: http://pastebin.com/Nb08Dtqk
I am getting NullPointerExceptions that seem to be stemming from this method here. Please help if you see anything clearly wrong with my code.
‑‑‑‑‑
參考解法
方法 1:
I didn't read through all your code but I found this:
public void addFirst(E dataItem) {
Node<E> node = new Node <E>(dataItem, null, null);
// To be completed by the student
if (head == null) // list is empty
head = head.previous = node;
else {
node.next = head;
head.previous = node;
head = node;
}
count++;
}
Possible culprit,
if (head == null) // list is empty
head = head.previous = node;
In this statement, head.previous = node;
is being done first, but head
is still null. NullPointerException is being thrown before head
is set to anything.
If head is null you definitely don't want to do head.previous
方法 2:
Without more information, I'd have to guess head
is probably null.
(by Eddie Macleod、Lews Therin、Skip Head)