I have a task which involves passing array values (writing) into a text (.txt) file in Java. This is my first time using BufferedWriter and I've tried quite a few variations on if statements, but can't see to get my program to write in the format matrix[i][j] + "," until it hits the last column index and writes without the comma after the integer.
I tried using the append() method that BufferedWriter extends but I don't think I used it correctly.
Current Code
void writeMatrix(String filename, int[][] matrix) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
bw.write(matrix[i][j] + ",");
}
bw.newLine();
}
bw.flush();
} catch (IOException e) {}
}
Current Output
1,2,3,
4,5,6,
7,8,9,
I need the last digit on each line to not include the comma and BufferedWriter apparently doesn't like to add two write() methods together on the same line. So how could I do this?
You can change your innermost for loop to this:
for (int j = 0; j < matrix[i].length; j++) {
bw.write(matrix[i][j] + ((j == matrix[i].length-1) ? "" : ","));
}
This puts a simple ternary operator in that does this:
if j is last index:
)else
,)On request, this would be the equivalent to this if-else statement:
for (int j = 0; j < matrix[i].length; j++) {
if(j == matrix[i].length-1) {
bw.write(matrix[i][j]);
} else {
bw.write(matrix[i][j] + ",");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With