简体   繁体   中英

Condition in while loop doesn't work?

private void Scan(DoublyLinkedList dList) { // T(n) = O(n)
    DNode p1 = dList.getFirst();

    while (p1 != null) {
        DNode p2 = p1.next;
        System.out.println(p1.getElement().toString()); // <--- Here it throws NullPointerException.

        if (p2.next != null) {
            DNode p3 = p2.next;

            if (p3.getElement() != null) {
                boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());

                if (b == true) {
                    p1 = p1.next;
                } else {
                    p1.next = p3;
                    p3.prev = p1;
                    dList.remove(p2);
                    p1 = p1.prev;
                }
            } else break;
        }else break;
    }
}

the exception:

run:
Exception in thread "main" java.lang.NullPointerException
X :8.0  Y: 9.0angle0.0lol
        at ConvexHull.GrahamVersion.Scan(GrahamVersion.java:102)
        at ConvexHull.GrahamVersion.grahamScan(GrahamVersion.java:83)
        at ConvexHull.GrahamVersion.<init>(GrahamVersion.java:25)

It throws NullPointerException on System.out.println(p1.getElement().toString()); . It means that it doesn't pay attention to the condition of while loop?

p1 is not null , but p1.getElement() returned null .

Remove the toString() call. You don't need it there in sysout. It will then just print null as "null".

The condition in the while loop does work. The NullPointerException is thrown on p1.getElement() , which is null and therefore cannot be dereferenced. If p1 were null , the line above it ( p2 = p1.next ) would fail.

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