This can take pretty much anything you can throw at it:
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 3, 4, 5, 6 },
{ 2, 3, 4, 5, 6, 1 },
{ 3, 4, 5, 6, 1, 2 },
{ 4, 5, 6, 11, 2, 3 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 223523526, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 5, 116, 1, 2, 3, 4 },
{ 6, 1, 2, 3, 4, 5 }
};
//compute the maximum header width (the number of columns)
int rows = matrix.length;
int cols = rows > 0 ? matrix[0].length : 0;
int maxRowHeaderWidth = Integer.toString(rows).length();
int maxCellWidth = 1;
//compute the maximum cell width
for ( int[] row : matrix ) {
for ( int cell : row ) {
maxCellWidth = Math.max(Integer.toString(cell).length(), maxCellWidth);
}
}
maxCellWidth = Math.max(maxCellWidth, Integer.toString(cols).length());
StringBuilder patternBuilder = new StringBuilder();
//the header
for ( int i = 0; i < maxRowHeaderWidth; i++ ) {
patternBuilder.append(' ');
}
patternBuilder.append('|');
for ( int i = 0; i < cols; i++ ) {
patternBuilder.append(String.format("%" + (maxCellWidth+1) + "d", i+1));
}
patternBuilder.append('\n');
//the line of dashes
int rowWidth = patternBuilder.length();
for ( int i = 0; i < rowWidth; i++ ) {
patternBuilder.append('-');
}
patternBuilder.append('\n');
//each row
for ( int i = 0; i < matrix.length; i++ ) {
patternBuilder.append(String.format("%" + (maxRowHeaderWidth) + "d|", i+1));
for ( Integer cell : matrix[i] ) {
patternBuilder.append(String.format("%" + (maxCellWidth+1) + "d", cell));
}
patternBuilder.append('\n');
}
System.out.println(patternBuilder);
}
It sizes every cell equally, regardless of the length of the number in the cell. It can take an arbitrary number of rows or columns.