[英]Print A 2D Array As A Grid? (Java)
在我一直从事的个人Java项目中,我遇到了一个难题。 我想以表格的形式打印一个二维的字符串数组。 不是字符串本身,而是行和列标签(请考虑使用Microsoft Excel)。 这就是我所预想的最终产品,带有星号的代表字符串应该放哪里。
| A | B | C | D | E | F | G |
----+---------+---------+---------+---------+---------+---------+---------+
1 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
2 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
3 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
4 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
5 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
6 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
7 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
8 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
9 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
10 | * | * | * | * | * | * | * |
----+---------+---------+---------+---------+---------+---------+---------+
我知道这将使用嵌套的前向循环,并且逻辑过程是将String值放入内部循环,例如“ example [i] [j]”类型格式。 我对如何以正确的格式围绕单元格进行设计感到困惑,将每个String限制为10个字符,就像Excel缩小时如何限制其单元格大小一样。 我是否为此使用子字符串? 我是否使用printf来使第10行正确间隔?
任何指针都将不胜感激,我从未像现在这样陷入困境。
第一行应该很容易,假设您不超过26列,即列名只是A
到Z
偶数行都是----+
的导入,其后是---------+
columnCount重复。
奇数行(第一行除外)的引入为999 |
,其中999
是右对齐的行号,前导空格。 可以使用printf()
或String.format()
的格式字符串为
"%3d |"
。
在导入之后,是字符串计数的columnCount重复项,将其修剪并居中对齐为9个字符,后跟|
。
要居中对齐9个字符,请执行以下操作:
substring()
)。 spacesTotal = 9 - trimmedLength
。 spaceBefore = spacesTotal / 2
。 spaceAfter = spacesTotal - spaceBefore
。 spaceBefore
,(修剪后的)文本值, spaceAfter
和|
。 public static void printStringGrid(String[][] array){
System.out.print(" |");
for (int i = 0; i < array[0].length; i++){
System.out.print(" ");
System.out.print((char)('A' + i));
System.out.print(" |");
}
System.out.println();
for (int i = 0; i < array.length; i++){
System.out.print("----+");
for (int j = 0; j < array[0].length; j++){
System.out.print("---------+");
}
System.out.println();
System.out.print(" " + (i + 1) + " |");
for (int j = 0; j < array[0].length; j++){
if (array[i][j].length() < 10){
int spaces = (9 - array[i][j].length()) / 2;
for (int k = 0; k < spaces; k++){
System.out.print(" ");
}
System.out.print(array[i][j]);
for (int k = 0; k < (9 - array[i][j].length()) - spaces; k++){
System.out.print(" ");
}
}
else{
System.out.print(array[i][j].substring(0, 9));
}
System.out.print("|");
}
System.out.println();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.