My input file is under the form:
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
I am reading this file and storing it into a list of strings as follows, then I am splitting each line by the comma. The number in the middle is incremented after 8 lines and I would like to print =============== only if it is incremented by more than one. My current output is the following:
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();
}
}
}
Here is my output:
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
This is incorrect as I would only like to print ====================== if the middle number is incremented by more than 1. The correct output should be the following:
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
How can I fix this?
I think you were on the right path and you just had the wrong comparetion in your if
statement. Also I did some tweaks in your code to simplify it a little bit.
public static void main(String[] args) {
try {
List<String> list = Files.readAllLines(Paths.get("C:\\Users\\mouna\\ownCloud\\Mouna Hammoudi\\dumps\\Python\\dataMachineLearning.txt"));
int last = 0;
for(String myLine : list) {
String[] array = myLine.split(",");
int counter = Integer.parseInt(array[0]);
int num = Integer.parseInt(array[1]);
if(counter == 1 && num > last+1) {
System.out.println("======");
}
System.out.println(array[0]+" "+array[1]+" "+array[2]);
last = num;
}
} catch (IOException e) {
e.printStackTrace();
}
}