![](/img/trans.png)
[英]Creating an object of one class in another, what is the relationship in a UML class diagram?
[英]Creating an object of one class in another class?
我有兩個類,我想知道為什么在嘗試使用“ Graph”類的方法創建“ Knoten”類的對象時總是出現錯誤。
類圖
public class Graph
{
static Knoten[] knotenliste;
public void punktHinzufuegen(int x, int y){
for(int i=0;i<Gui.zaehler;i++){
knotenliste[i]=new Knoten(x,y);
}
}
}
結類:
public class Knoten{
int xPos;
int yPos;
public Knoten(int x,int y){
xPos=x;
yPos=y;
}
}
每次我調用punktHinzufuegen方法時,都會收到一個錯誤。 感謝您的幫助。
您的問題是一個非常容易解決的問題,因此,我將給出簡短的解釋/解決方案。
您當前的問題是,您沒有定義knotenliste 。 您應該將其定義為以下字段:
private static Knoten[] knotenliste = new Knoten[Gui.zaehler];
我建議您不要使用靜態值,而是開始使用固定的ArrayList (以便為圖形點建立索引)或Queue 。 如果您對閱讀它們有所了解,那么可以在Java文檔中找到這兩者。 我要做的是以下幾點:
public class Graph {
private final ArrayList<Knoten> knotenliste = new ArrayList<>(Gui.zaehler);
public void punktHinzufuegen(int x, int y) {
for (int i = 0; i < Gui.zaehler; i++) {
// Keep in mind that the List#add(int index, E element) will
// shift all the elements previously in the array to the right.
knotenliste.add(i, new Knoten(x, y));
}
}
}
這樣,您不僅可以停止濫用static關鍵字,而且還可以使用更靈活的Collection來保存Knoten。
您尚未初始化數組,我認為添加元素時會收到NullPointerException
。 您需要先初始化它,然后再向其中添加元素
static Knoten[] knotenliste = new Knoten[<SOME_INT_VALUE>];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.