简体   繁体   中英

I keep getting wrong output or null pointer exception in my towers program

I'm working on solving towers game by using stacks and linked lists and moving blocks from tower to tower by using recursion.

I encountered a problem in my problem which causes java.lang.NullPointerException. My guess why this was happening was that I try to pop value from a stack even when there are no entries. After I put bound control I still receive that error.

Th error points to the line with deleteFirst() method but I don't see why this would happens even after I check if lists are empty.

My task here was just to pass towers or LinkedStack objects then move the content of theirs in tower game fashion.

Errors:

Exception in thread "main" java.lang.NullPointerException
    at LinkList.deleteFirst(towers.java:47) // code with: **first = first.next;**
    at LinkedStack.pop(towers.java:82) // code with: return theList.deleteFirst();
    at LinkListApp.doTowers(towers.java:146) // code with: A.pop();
    at LinkListApp.doTowers(towers.java:140) // doTowers(a-1, A, C, B);
    at LinkListApp.main(towers.java:121) // doTowers(nDisks, linkA, linkB, linkC);

What am I doing wrong here? I can't make this work. as it should.

Your doTowers call makes calls to A.pop() and C.pop(), neither of which is protected. Your LinkedStack directly calls theList.deleteFirst() without an empty check, and your deleteFirst method calls first = first.next without checking if first is null or not. It would be good to make your LinkedList smart enough that deleteFirst doesn't throw a NPE in this case, then you won't need special checks all over the place in the upper layers. To do that, change deleteFirst to something like

public long deleteFirst()
{
    if ( first != null ) {
        Link temp = first;
        first = first.next;
        return temp.dData;
    }
    else {
        return whateverIndicatesTheListIsAlreadyEmptyWhichMayBeHardWithReturnTypelong;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM