如何初始化PrintWriter数组?

huangapple go评论85阅读模式
英文:

How to initialize PrintWriter array?

问题

我必须创建 n 个文件n 是随机的但它将在 1<=n<=7 的范围内当我运行这个程序时它会出现 NullPointException空指针异常)。file_num 是要创建的文件数量如果我从第一行中删除 null它会告诉我要初始化数组

PrintWriter[] writer = null;
for (int j = 0; j < file_num; j++) {
    System.out.println("J is " + j);
    writer[j] = new PrintWriter(new File("file" + (j + 1) + ".csv"));
}
英文:

I have to create n number of files. N is random but it will be in this range 1<=n<=7. When I run this program it gives NullPointException. file_num is number of files to be created. If I remove null from the first line it tells me to initialize the array.

PrintWriter[] writer=null;
for(int j=0;j&lt;file_num;j++)
{
	System.out.println(&quot;J is &quot;+j);
	writer[j] =new PrintWriter(new File(&quot;file&quot;+(j+1)+&quot;.csv&quot;));
}

答案1

得分: 0

当我运行这个程序时,它会产生空指针异常。

这是因为

 PrintWriter[] writer = null;

你应该用大小为 file_num 的新空数组初始化 writer 数组

PrintWriter[] writer = new PrintWriter[file_num];
英文:

> When I run this program it gives NullPointException.

That's because

 PrintWriter[] writer = null;

You should initialize writer array with new empty array of size file_num

PrintWriter[] writer = new PrintWriter[file_num];

huangapple
  • 本文由 发表于 2020年1月30日 19:36:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/59985157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定