2014-02-05 43 views
2

有誰知道爲什麼我不能追加一個字符到這個StringBuffer數組(在我的例子中),有人可以告訴我我需要怎麼做?不能追加char到一個StringBuffer二維數組

public class test { 
    public static void main(String args[]){ 

     StringBuffer[][] templates = new StringBuffer[3][3]; 

     templates[0][0].append('h'); 
    } 
} 

我輸出到這個代碼是:

output:  Exception in thread "main" java.lang.NullPointerException 
      at test.main(test.java:6) 

這將幫助我這麼多,所以如果你知道的任何解決方案,請回覆此

+0

代碼按設計工作。 –

回答

1

您需要在之前初始化緩衝區迴應附加的東西

templates[0][0] = new StringBuffer();

3

下面的語句WIL我只是聲明數組,但不會initalize它的元素:

StringBuffer[][] templates = new StringBuffer[3][3]; 

你需要努力的內容附加到他們之前來初始化數組元素。不這樣做將導致NullPointerException

添加此初始化

templates[0][0] = new StringBuffer(); 

然後追加

templates[0][0].append('h'); 
0

其他正確地指出了正確的答案,但會發生什麼,當你試圖做類似templates[1][2].append('h');

你真正需要的是這樣的:

public class Test {   //<---Classes should be capitalized. 

    public static final int ARRAY_SIZE = 3; //Constants are your friend. 

    //Have a method for init of the double array 
    public static StringBuffer[][] initArray() { 
     StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE]; 
     for(int i = 0;i<ARRAY_SIZE;i++) { 
      for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer(); 
     } 
     return array; 
    } 

    public static void main(String args[]){ 

     StringBuffer[][] templates = initArray(); 

     templates[0][0].append('h'); 
     //You are now free to conquer the world with your StringBuffer Matrix. 
    } 
} 

使用常數是重要的,是合理的預期你的矩陣大小改變。通過使用常量,您可以將其更改爲僅在一個位置,而不是分散在整個程序中。

相關問題