-1

我有一个字符数组。我必须在第三个字符之后插入“,”。我已经编写了以下代码。

    public class Comma {
    char [] str = {'1','2','3','4','5','6','7','8','9'};
    char [] buf = null;
    int size = str.length;
    int c=1;
    public void insert()
    {
      for(int i=0;i<size+10;i++)
      {
        c++;
        if(c==3)
        {
            buf[i]=',';
            i++;
            c=1;
        }
        buf[i]=str[i];
    }   
    for(int i=0;i<buf.length;i++)
    System.out.println("Final String is"+buf[i]);
   }
   public static void main(String args[])
   {
      Comma c = new Comma();
      c.insert();
   }
   }

当我运行它时,它显示空指针异常。我哪里做错了?

4

9 回答 9

6

char [] buf = null;声明为null并且您正在访问它 buf[i]=',';

尝试声明

char [] buf=new char[some range];

例子:

 char [] buf=new char[8];
于 2013-06-28T11:10:52.977 回答
2

您使用buf.length了 ,但您的 buf 被声明为空。

于 2013-06-28T11:11:24.950 回答
2

您尚未初始化char buf[],您正在尝试为其赋值。您需要按如下方式对其进行初始化,

char [] buf=new char[10];

然后使用它,否则它会抛出 NullPointerException。

于 2013-06-28T11:13:39.867 回答
1

在java中,您必须在第一次创建数组时给出数组大小,之后就不能更改了。所以你会想要机会

char [] buf = null;

进入

char [] buf = new char[10];

这样,您实际上将为要放置的字符保留空间。

于 2013-06-28T11:18:04.493 回答
1

初始化如下

 char [] buf =new char[somevalue] ;
于 2013-06-28T11:18:48.030 回答
0

buf is an array of size null. Hence the null pointer exception.

于 2013-06-28T11:16:04.420 回答
0

Here you declared char [] buf = null; as null and you are accessing it.

So buffer is null.So it is giving here NullPointerException.

Solution:

char [] buf = char[10];
于 2013-06-28T11:16:13.883 回答
0

initialize your array with some size

 char [] buf = char[size];
于 2013-06-28T11:16:47.443 回答
0

Because you have not initialize yr buf

use this

char [] buf = new char[str.length];
于 2013-06-28T11:17:17.143 回答