2012-04-03 25 views
1

我想要如在上述代碼getNumber如下的NullPointerException而在2維陣列訪問方法,在一個對象中

public static void main(String[] args) throws IOException { 
      length=getNumber("Enter the length of the field: "); 
      breadth=getNumber("Enter the breadth of the filed: "); 
      node n = new node(); 
      node [][] field = new node[length][breadth]; 
      for(i=0;i<=length;i++){ 
       for(j=0;j<=breadth;j++){ 
        F =getNumber("Enter the F value"); 
        field[i][j].setF(F); 
        System.out.println(" "+field[i][j].getF(F); 
       } 
      } 

    } 

製造「節點」的對象的2維陣列是一個函數式中,i和打印接受數 這裏是我的節點類:

public class node { 
public int F; 
public int G; 
public int H; 
public boolean isVisited; 
public boolean isCurrent; 
public void node(int F,int G,int H,boolean isVisited, boolean isCurrent){ 
    this.F=F; 
    this.G=G; 
    this.H=H; 
    this.isVisited=isVisited; 
    this.isCurrent=isCurrent; 

} 
public int getF() { 
    return G+H; 
} 
public void setF(int f) { 
    F = f; 
} 
public int getG() { 
    return G; 
} 
public void setG(int g) { 
    G = g; 
} 
public int getH() { 
    return H; 
} 
public void setH(int h) { 
    H = h; 
} 
public boolean isVisited() { 
    return isVisited; 
} 
public void setVisited(boolean isVisited) { 
    this.isVisited = isVisited; 
} 
public boolean isCurrent() { 
    return isCurrent; 
} 
public void setCurrent(boolean isCurrent) { 
    this.isCurrent = isCurrent; 
} 

}

所有我想要做的是,存儲/每一F,G,H等的接入各種值的節點對象,但問題是我得到java.lang.NullPointerExceptionfield[i][j].setF(F); 我不知道我要去哪裏錯了,需要一些幫助。

回答

2

您初始化了該數組,但未填充該數組。

考慮這條線:

field[i][j].setF(F);

當你

field[i][j]

您正在訪問的陣列;即獲取該位置陣列中的內容。既然你沒有把任何東西放在數組中,你會得到一個null。但你立即嘗試撥打setF

我注意到你做

node n = new node();

外循環。你可能想在循環中做到這一點。

node n = new node(); 
n.setF(F); 
field[i][j] = n; 

此代碼創建node實例,設置在其上的值,然後在指定的位置把它在數組中。有一點更看中的辦法是做類似

node n = field[i][j]; 
if (n == null) { // initialize n at the position if it doesn't exist 
    n = new node(); 
    field[i][j] = n; 
} 

field[i][j].setF(f); 

或者,您可以循環在陣列上,換上新node在每個位置,之後你初始化數組。

最後,在Java標準實踐中是用大寫字母開始類名。 node應該是Node

+0

我該如何填充它?因爲它的對象數組(我是一個初學者如此詳細地闡述) – md1hunox 2012-04-03 13:03:10

+0

@vineetrok檢查我的答案的底部,在那裏我詳細說明。 – hvgotcodes 2012-04-03 13:04:45

+0

非常感謝,現在就在工作 – md1hunox 2012-04-03 13:11:35

0

試試這個:在java中

for(i=0;i<=length;i++){ 
    for(j=0;j<=breadth;j++){ 
     F =getNumber("Enter the F value"); 

     node tmp = new node(); 
     tmp.setF(F); 

     field[i][j] = tmp; 
     System.out.println(" "+field[i][j].getF(F); 
    } 
} 

PS是約定類名開始與資本,應在駝峯寫

[編輯] 小心你的GET/SETF( )的功能,因爲它們不在相同的變量上運行

與您的問題沒有關係,但您可能需要通讀此document這將教您如何使用java命名約定,並幫助您編寫代碼爲e asier閱讀

+0

使用此我得到字段[i] [j] .getF(F)= 0 – md1hunox 2012-04-03 13:22:00

+0

好吧,你的「節點」沒有正確初始化,它沒有構造函數,默認的離開G和H在0 ... (你的代碼在這裏相當混亂),因爲setF()實際上設置F,但getF()返回G + H。公共無效節點()是沒有構造函數構造函數將公共節點() – Grims 2012-04-03 13:33:02

+0

那!現在就開始工作吧!謝謝! – md1hunox 2012-04-03 13:43:51