簡體   English   中英

遍歷圖的邊和頂點時發生NullPointerException

[英]NullPointerException while Looping through Edges and Vertices of Graph

我試圖遍歷圖中的頂點,並在行進時列出其邊緣。 到目前為止,我已經能夠提出以下代碼:

public String displayRecords()
{
    String printOut = null;
    for (ListIterator<Vert> iter = graph.listIterator(); iter.hasNext(); ) 
    {
        Vert displayVert = iter.next();
        boolean cont = true;
        int floop = 0;
        Edge tempEdge = null;
        //extra vars
        String pname = null;
        String sname = null;
        int dist = 0;
        do
        {
            if(floop == 0)
            {
                tempEdge = displayVert.firstEdge;
                pname = displayVert.name;
                sname = tempEdge.parentNode.name;
                dist = tempEdge.edgeLen;
                floop++;
            }else{
                tempEdge = tempEdge.nextEdge; 
            }

            printOut = printOut + pname + sname + dist + "Plane";

        }while(tempEdge.nextEdge.parentNode != null);
    }
    return printOut;
}

但是,我在這一行不斷收到NullPointerException

}while(tempEdge.nextEdge.parentNode != null);

這是我的VertEdge類的代碼:

class Vert {
   public Edge firstEdge;
    public String name; 
   // other node info here

   public Vert() {
      firstEdge = null;

   }

    public Vert(String n)
    {
        firstEdge = null;
        name = n;   
    }
}

class Edge {
   public Vert parentNode = null; 
   public Edge nextEdge = null; // next in adj list
   // other edge info here
   public int edgeLen; // edge length

   public Edge(Vert num, Edge e, int len) {
      parentNode = num;
      nextEdge = e;
      // initialize other edge info here
      edgeLen = len;
   }

}

我在做什么錯,有沒有更簡單的方法可以做到這一點?

您將tempEdge設置為null,並將floop0 ,這意味着else語句將運行。 我覺得這就是NullPointerException發生的地方。 否則,如果未將nextEdge字段設置為任何null ,則該字段將為null ,當您嘗試通過此null項目訪問字段parentNode時,將獲得NullPointerException

可以將tempEdge初始化為null以外的其他null ,或者將while循環更改為:

while(tempEdge.nextEdge != null && tempEdge.nextEdge.parentNode != null);

如果nextEdge字段為null ,它將中斷。 如果不是,則可以安全地繼續進行下一個條件,這是您真正要測試的條件。

這是您的問題:

tempEdge = tempEdge.nextEdge;

如果讓循環運行足夠長的時間,最終將tempEdge設置為null ,然后在此處設置條件:

}while(tempEdge.nextEdge.parentNode != null);

將拋出NullPointerException 您可能想將其修改為

}while(tempEdge != null && tempEdge.parentNode != null);

這樣,當tempEdgenull ,即當您超出列表邊緣時,或者當parentNodenull時,do while循環將中斷。

很酷的事情是,如果tempEdge實際上為null ,則條件在檢查tempEdge.parentNode之前將評估為false,因此該條件永遠不應拋出NullPointerException

現在,如果在此之后您仍然收到NullPointerException ,則唯一的答案是,第一次使用它時它就壞了。 即使不滿足條件,do while循環也始終運行一次。 如果發生這種情況,這意味着你的第一個tempEdge有一個null parentNode ,這可能是一個設計問題比什么都重要。

暫無
暫無

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

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