【发布时间】:2021-05-07 02:53:49
【问题描述】:
我的输入文件的格式如下:
1,1,1
2,1,0
3,1,0
4,1,0
5,1,0
6,1,0
7,1,0
8,1,0
1,3,0
2,3,0
3,3,0
4,3,0
5,3,0
6,3,1
7,3,1
8,3,0
1,4,0
2,4,1
3,4,0
4,4,0
5,4,0
6,4,0
7,4,0
8,4,1
1,5,1
2,5,0
3,5,0
4,5,0
5,5,0
6,5,0
7,5,1
8,5,1
我正在读取这个文件并将其存储到一个字符串列表中,如下所示,然后我用逗号分隔每一行。中间的数字在 8 行后递增,我想打印 =============== 仅当它增加超过一时。我目前的输出如下:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFileLineByLineUsingBufferedReader {
public static void main(String[] args) {
BufferedReader reader;
List<String> mylist= new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(
"C:\\Users\\mouna\\ownCloud\\Mouna Hammoudi\\dumps\\Python\\dataMachineLearning.txt"));
String line = reader.readLine();
while (line != null) {
// read next line
mylist.add(line);
line = reader.readLine();
}
int counter=0;
int last=-1;
for(String myline: mylist) {
String[] splitted = myline.split("\\,");
System.out.println(splitted[0]+" "+splitted[1]+" "+splitted[2]);
int num=Integer.parseInt(splitted[1])+1;
counter++;
if(counter%8==0 && num!=last-1) {
System.out.println("=============================================");
}
last=num;
if(counter==8) {
counter=0;
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是我的输出:
1 1 1
2 1 0
3 1 0
4 1 0
5 1 0
6 1 0
7 1 0
8 1 0
=============================================
1 3 0
2 3 0
3 3 0
4 3 0
5 3 0
6 3 1
7 3 1
8 3 0
=============================================
1 4 0
2 4 1
3 4 0
4 4 0
5 4 0
6 4 0
7 4 0
8 4 1
=============================================
1 5 1
2 5 0
3 5 0
4 5 0
5 5 0
6 5 0
7 5 1
8 5 1
这是不正确的,因为我只想打印 ======================= 如果中间数字增加超过 1。正确的输出应该如下:
1 1 1
2 1 0
3 1 0
4 1 0
5 1 0
6 1 0
7 1 0
8 1 0
=============================================
1 3 0
2 3 0
3 3 0
4 3 0
5 3 0
6 3 1
7 3 1
8 3 0
1 4 0
2 4 1
3 4 0
4 4 0
5 4 0
6 4 0
7 4 0
8 4 1
1 5 1
2 5 0
3 5 0
4 5 0
5 5 0
6 5 0
7 5 1
8 5 1
我该如何解决这个问题?
【问题讨论】:
-
将当前迭代的中间数存储在单独的变量中。在下一次迭代中,将其与此值进行比较以检查是否大于 1 个案例。
-
请注意,您可以将整个“读取文件”循环替换为
List<String> lines = Files.readAllLines(Path.of("myFile.txt"));。
标签: java arrays list increment