接收空指针异常

时间:2013-11-27 02:42:06

标签: java nullpointerexception

我创建了一个从列表中获取优势的函数:

这是我的代码:

public EdgeNode getEdge(int ind)
{
    EdgeNode t = edges.start;
    for (int i = 0; i < ind; i++)
    {
        t = t.next;
        if (t.next == null)
            break;
    }
        return t;

}

我收到一个空指针错误,它指向该函数,我不知道出了什么问题。它一直在崩溃,有人可以帮助我吗?

这是错误:

Exception in thread "main" java.lang.NullPointerException
at MST.findMST(MST.java:45)
at Test.main(Test.java:21)

Edgenode:

public class EdgeNode
{
    int u;
    int v;
    int weight;
    EdgeNode next;

//  If the edges weights are the same then compare the
//  edge names lexicographically.

    public boolean lessThan(EdgeNode edge)
    {
        if (weight < edge.weight)
            return true;
        else if (weight == edge.weight)
        {
            if (u < edge.u)
                return true;
            else if (u > edge.u)
                return false;
            else if (u == edge.u)
                if (v < edge.v)
                    return true;
                else
                    return false;
        }
        else if (weight < edge.weight) {
            return false;
}
        return false;
    }

    public EdgeNode(int x, int y, int w)
    {
        u= x; 
        v= y; 
        weight=w;
        next= null;
    }
    public void print()
    {
        System.out.format("(%3d, %3d):%3d  ", u, v, weight);
    }
}

第44/45行:

EdgeNode temp = G.getEdge(k);
int u = temp.u;

下面:

C:\Users\John\Desktop\updated>javac Test.java

C:\Users\John\Desktop\updated>java Test < one.txt
The edges in the graph:
(  0,   1):  1  (  0,   2):  3  (  0,   3):  1  (  1,   2):  2  (  1,   3):  1

(  2,   3):  2
4
Exception in thread "main" java.lang.NullPointerException
        at MST.findMST(MST.java:45)
        at Test.main(Test.java:21)

4 个答案:

答案 0 :(得分:0)

如果你没有节点,那么第一行中的t.next将导致NullPointerException。 因此,首先需要检查是否存在节点,然后查看是否存在下一个节点。即Edges.start()可能不会返回任何值。因此首先检查t!=null是否然后获取t.next()

答案 1 :(得分:0)

我假设t是一些东西的列表。如果列表t中的任何一个项为null,则只要它被发现,程序就会立即退出循环并返回该空指针。因此NullPointerException。

答案 2 :(得分:0)

EdgeNode t = edges.start;

可能没有正确初始化边缘,并获得空值。

答案 3 :(得分:-1)

如果“t = t.next;”为null,您仍在使用“t.next == null”,这会导致空指针异常

相关问题