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
To properly format numbers in columns, it's best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern "%4d"
. For instance to allow any integer between Integer.MIN_VALUE
and Integer.MAX_VALUE
, use "%12d"
.
public void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.printf("%4d", matrix[row][col]);
}
System.out.println();
}
}
Example output:
36 913 888 908
732 626 61 237
5 8 50 265
192 232 129 307