簡體   English   中英

接收空指針異常

[英]Receiving Null Pointer Exception

我做了一個函數來從列表中獲取優勢:

這是我的代碼:

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)

邊緣節點:

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)

如果u沒有節點,則第一行中的t.next本身將導致NullPointerException 因此,首先需要檢查是否有一個節點,然后查看是否有下一個節點。 即Edges.start()可能不會返回任何值。 因此首先檢查t!=null是否t!=null ,然后獲取t.next()

我假設t是某物的某個列表。 如果列表t中的任何一項為null,則一旦發現,程序將立即退出循環並返回該null指針。 因此,NullPointerException。

EdgeNode t = edges.start;

邊緣可能未正確初始化,並獲得了空值。

如果“ t = t.next;” 為null,您仍在使用“ t.next == null”,這會導致空指針異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM