這可能需要相當多的東西,你可以扔掉它:
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);
}
它尺寸爲每一個細胞都一視同仁,無論在細胞數量的長度。它可以佔用任意數量的行或列。
是的我相信你的代碼塊顯示它是動態的,授予我沒有運行代碼 – Woot4Moo 2010-10-21 15:07:13
雅,它是什麼Q.? – 2010-10-21 15:11:09
如何動態地在表格佈局中包裝表格內容 – 2010-10-21 15:12:14