Hi I am trying to write a csv file with some data, I want to compare elements in the EMPTY_Columns array against the MY_HEADERS array, if they are the same I want to write in empty string, if they are different I want to write in some data.
I made a boolean function to check if headings are the same so that I could write an empty string into those columns and move to the next line
private boolean sameHeaders(String[] A, String[] b) {
for(int i = 0; i <= a.length - 1; i++) {
if(a[i].equals(b[i]))
return true;
}
return false
}
I call this function my other one for writing the csv data into the csv
private void writeCsvData(File csv, List<MyReport> reports) {
try (Buffered write = new BufferedWriter(new FilterWrite(csv))) {
write.write(getReportHeader());
writer.newLine();
for(MyReport report : reports) {
if(!sameHeaders(MY_HEADERS, EMPTY_COLUMNS)) {
writer.write(getReportData(report));
writer.newLine();
} else {
writer.write("")
writer.newLine();
}
}
writer.flush();
} catch (exception e) {
//errors and exception logging
}
I thought something like this would work but now its just writing empty strings into the csv anyone got some pointers on where I am going wrong?
I wrote a basic JUnit-Test, which could help to clarify what you're trying to do. First of all I've put your code in a class called
HeaderComparator.javawith the following content:It's basically the same method you have provided. After that, I wrote a JUnit-Test to compare 2 headers, called
MY_HEADERSandEMPTY_COLUMNS, in order to test your expectation:The first test passes, which is correct according to your expectation (the headers are the same). However, the second and the third test both fail, which of course is not correct, since the headers are different and you want the function to return
false, when the headers are not the same. So I guess, the problem with your function is, that it returnstrueas soon as two elements at the same index (e. g.a[1] = "Header2"andb[1] = "Header2"in the second and third test I provided) are the same. That is probably not what you want. You want them all to be the same, right?So maybe you want something like this:
That makes all Unit-Tests pass. However, your function would require the two arrays to contain the columns in the exact same order.