【问题标题】:Can't append char to a StringBuffer 2-dimensional array无法将 char 附加到 StringBuffer 二维数组
【发布时间】:2014-02-05 16:00:51
【问题描述】:

有谁知道为什么我不能在这个 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)

这对我很有帮助,所以如果你知道任何解决方案,请回复这个

【问题讨论】:

  • 代码按设计工作。

标签: java arrays char append stringbuffer


【解决方案1】:

下面的语句只会声明一个数组,但不会初始化它的元素:

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

在尝试将内容附加到它们之前,您需要初始化数组元素。不这样做会导致NullPointerException

添加这个初始化

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

然后追加

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

【讨论】:

    【解决方案2】:

    您需要在追加内容之前初始化缓冲区

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

    【讨论】:

      【解决方案3】:

      其他人正确指出了正确答案,但是当您尝试执行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.
          }
      }
      

      使用常量很重要,因为可以合理地预期您的矩阵大小会发生变化。通过使用常量,您可以只在一个位置更改它,而不是分散在整个程序中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 2017-08-15
        相关资源
        最近更新 更多