I'm assuming by "look like a matrix", you mean equidistant spacing between the elements of the matrix.
Here's something I came up with.
1 3 4
-124 52 6
1 2 3 4
5 6 7 8
-9 -8 -7 -6
2 3 4 5
7 8 9 10
-12 -11 -10 -9
The "trick" is to find the element that takes the most characters to print and use that length plus one to get the spacing between the cells on the line.
The String
class has a format
method that will format an int
into a String
. The formatter "%4d" will take an int
and make it a four-character String
with leading spaces.
We can construct a formatter by putting the three pieces of a formatter together.
String formatter = "%" + width + "d";
Here's the complete runnable code.
public class MatrixPrint {
public static void main(String[] args) {
MatrixPrint mp = new MatrixPrint();
int[][] matrix1 = {{1, 3, 4},
{-124, 52, 6}};
System.out.println(mp.printMatrix(matrix1));
int[][] matrix2 = {{1, 2, 3, 4},
{5, 6, 7, 8},
{-9, -8, -7, -6}};
System.out.println(mp.printMatrix(matrix2));
int[][] matrix3 = {{2, 3, 4, 5},
{7, 8, 9, 10},
{-12, -11, -10, -9}};
System.out.println(mp.printMatrix(matrix3));
}
public String printMatrix(int[][] matrix) {
int width = largestWidth(matrix) + 1;
String formatter = "%" + width + "d";
return printMatrixElements(matrix, formatter);
}
private int largestWidth(int[][] matrix) {
int maxWidth = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int width = Integer.toString(matrix[i][j]).length();
maxWidth = Math.max(maxWidth, width);
}
}
return maxWidth;
}
private String printMatrixElements(int[][] matrix, String formatter) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
builder.append(String.format(formatter, matrix[i][j]));
}
builder.append(System.lineSeparator());
}
return builder.toString();
}
}