[英]Reading from a txt file into a single array - Java
I have a txt file that contains 40 names. 我有一个包含40个名字的txt文件。 Each name is on its own line. 每个名字都有自己的名字。 This method should take each name and place it into an array of 4 elements and then take that array and write those files to another txt file with use of another method. 此方法应该采用每个名称并将其放入一个包含4个元素的数组中,然后使用该数组并使用另一个方法将这些文件写入另一个txt文件。
My issue is every forth name in the list somehow ends up being null and my output txt file ends up with 10 rows and a null as the forth element in each row. 我的问题是列表中的每个名称都以某种方式结束为空,我的输出txt文件以10行结尾,并且每行的第四个元素为null。
I have provided code and sample I/O below. 我在下面提供了代码和示例I / O. Thanks in advance! 提前致谢!
Sample Input 样本输入
Emily
Reba
Emma
Abigail
Jeannie
Isabella
Hannah
Samantha
My method 我的方法
public static void fillArray(String[] player ,String[] team, BufferedReader br) throws IOException{
String line;
int count = 0;
while((line = br.readLine()) != null){
if(count < 3){
player[count] = line;
count++;
}
else{
count = 0;
writeFile(player);
}
}
br.close();
} }
Sample Output 样本输出
Emily Reba Emma null
Jeannie Isabella Hannah null
Your logic is incorrect. 你的逻辑不正确。 player[3]
is never set and the next loop you end up reading a line without storing it into the array. player[3]
永远不会被设置,下一个循环你最终会读取一行而不将其存储到数组中。 Use this: 用这个:
public static void fillArray(String[] player ,String[] team, BufferedReader br) throws IOException{
String line;
int count = 0;
while((line = br.readLine()) != null){
player[count] = line;
count++;
if (count == 4) {
count = 0;
writeFile(player);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.