How can I print out a simple int [][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn\'t apparently work. If it helps
In java8 fashion:
import java.util.Arrays;
public class MatrixPrinter {
public static void main(String[] args) {
final int[][] matrix = new int[4][4];
printMatrix(matrix);
}
public static void printMatrix(int[][] matrix) {
Arrays.stream(matrix)
.forEach(
(row) -> {
System.out.print("[");
Arrays.stream(row)
.forEach((el) -> System.out.print(" " + el + " "));
System.out.println("]");
}
);
}
}
this produces
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
but since we are here why not make the row layout customisable?
All we need is to pass a lamba to the matrixPrinter method:
import java.util.Arrays;
import java.util.function.Consumer;
public class MatrixPrinter {
public static void main(String[] args) {
final int[][] matrix = new int[3][3];
Consumer noDelimiter = (row) -> {
Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
System.out.println();
};
Consumer pipeDelimiter = (row) -> {
Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
System.out.println("|");
};
Consumer likeAList = (row) -> {
System.out.print("[");
Arrays.stream(row)
.forEach((el) -> System.out.print(" " + el + " "));
System.out.println("]");
};
printMatrix(matrix, noDelimiter);
System.out.println();
printMatrix(matrix, pipeDelimiter);
System.out.println();
printMatrix(matrix, likeAList);
}
public static void printMatrix(int[][] matrix, Consumer rowPrinter) {
Arrays.stream(matrix)
.forEach((row) -> rowPrinter.accept(row));
}
}
this is the result :
0 0 0
0 0 0
0 0 0
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
[ 0 0 0 ]
[ 0 0 0 ]
[ 0 0 0 ]