我有一个包含 40 个姓名的 txt 文件。每个名字都独占一行。此方法应获取每个名称并将其放入由 4 个元素组成的数组中,然后使用该数组并使用另一种方法将这些文件写入另一个 txt 文件。
我的问题是列表中的每个第四个名称都以某种方式最终为空,并且我的输出 txt 文件最终有 10 行,并且每行中的第四个元素为空。
我在下面提供了代码和示例 I/O。提前致谢!
示例输入
Emily
Reba
Emma
Abigail
Jeannie
Isabella
Hannah
Samantha
我的方法
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();
}
示例输出
Emily Reba Emma null
Jeannie Isabella Hannah null
最佳答案
你的逻辑不正确。 player[3]
永远不会被设置,并且下一个循环您最终会读取一行而不将其存储到数组中。使用这个:
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);
}
}
关于java - 从 txt 文件读入单个数组 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867245/