英文:
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<file_num;j++)
{
System.out.println("J is "+j);
writer[j] =new PrintWriter(new File("file"+(j+1)+".csv"));
}
答案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];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论