2012-05-25 252 views
0

嘿,到目前爲止我已經和我得到一個空指針錯誤在我的循環 任何人都知道爲什麼? 感謝c#實例化自定義對象

這裏是錯誤消息

對象引用不設置爲一個對象的一個​​實例。

board = new BoardSquare[15][]; 

    String boardHtml = ""; 

    for (int i = 0; i < 15; i++) { 
      for (int k = 0; k < 15; k++) { 
       //if (board[i][k] == null) 
        board[i][k] = new BoardSquare(i, k); 
       boardHtml += board[i][k].getHtml();//null pointer error here 
      } 
     } 

    /** 
    * A BoardSquare is a square on the FiveInARow Board 
    */ 
    public class BoardSquare { 
     private Boolean avail; //is this square open to a piece 
     private String color;//the color of the square when taken 
     private int x, y; //the position of the square on the board 

     /** 
     * creates a basic boardSquare 
     */ 
     public BoardSquare(int x, int y) { 
      avail = true; 
      this.x = x; 
      this.y = y; 
      color = "red";//now added (thanks) 
     } 

     /** 
     * returns the html form of this square 
     */ 
     public String getHtml(){ 
      String html = ""; 

      html = "<div x='" + x + "' y='" + y + "' class='" + (avail ? "available" : color) + "'></div>"; 

      return html; 
     } 

     /** 
     * if true, sets color to red 
     * if false, sets color to green 
     */ 
     public void takeSquare(Boolean red){ 
      if(red) 
       color = "red"; 
      else 
       color = "green"; 
     } 
    } 
+2

什麼的VS調試器顯示?如果連接到進程,它將在導致NRE的行上中斷,並且可以檢查變量/表達式的值。這會在以後成爲你的朋友,所以現在就習慣吧。 – 2012-05-25 00:57:08

+0

on boardHTML?如果在循環之前將它設置爲String.Empty。它不喜歡null + = ..... –

回答

1

是字符串場顏色實例化?看起來不像它。

有你的空。

html = "<div x='" + x + "' y='" + y + "' class='" + (avail ? "available" : color) + "'></div>"; 

構造函數應該是這樣的:

public BoardSquare(int x, int y) { 
      avail = true; 
      this.x = x; 
      this.y = y; 
      Color = "white"; 
     } 
+0

'html'上面的一行設置爲空字符串。' –

+0

啊,你的意思是「顏色」,我明白了。 –

+0

是的,忘了輸入:) –

0

你正在創建一個array of arrays(也被稱爲鋸齒數組),我不認爲這是你想要的。您可能正在尋找一個multidimensional陣列:

BoardSquare[,] board = new BoardSquare[15,15]; 

然後,當你分配給它:

board[i,k] = new BoardSquare(i, k); 
boardHtml += board[i,k].getHtml(); 
+0

那麼肯定有效。謝謝一堆。無論如何有什麼區別?我試圖找出,但無濟於事 – Gambai

+0

我添加了一個鏈接到鋸齒陣列的MSDN描述。 –