while循环中的条件不起作用?

时间:2010-11-27 05:02:45

标签: java nullpointerexception while-loop

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;
    }
}

例外:

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)

它会在NullPointerException上抛出System.out.println(p1.getElement().toString());。这意味着它没有注意while循环的条件吗?

2 个答案:

答案 0 :(得分:4)

p1不是null,但p1.getElement()返回null

删除toString()电话。你在sysout中不需要它。然后它会将null打印为“null”。

答案 1 :(得分:0)

while循环中的条件有效。 NullPointerException上会p1.getElement()抛出null,因此p1无法解除引用。如果nullp2 = p1.next,则其上方的行({{1}})将失败。