Java实现7x7海战矩阵:字母索引与列对齐问题求助
海战游戏7x7矩阵列对齐解决方案
问题说明
我正在用Java实现海战游戏的7x7战场矩阵,需要用数字(行索引)和字母(列索引)定位单元格,但控制台打印时字母列无法和矩阵单元格对齐,不能使用GUI,矩阵用'⛶'等字符填充。
当前代码
System.out.print(" A B C D E F G \n"); for (int i = 0; i < ROWS; i++) { System.out.print((i + 1) + " "); for (int j = 0; j < COLUMNS; j++) { System.out.print(campo[i][j] + " "); } System.out.println(" " + (i + 1)); } System.out.print(" A B C D E F G \n");
当前输出
A B C D E F G 1 ⛃ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ 1 2 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 2 3 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 3 4 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 4 5 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 5 6 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 6 7 ⛁ ⛶ ⛶ ⛶ ⛶ ⛶ ⛃ 7
解决方案
核心问题是控制台输出需要固定宽度的格式,手动加空格无法适配全角字符(比如'⛶'占2个半角字符宽度),因此要用Java的格式化输出统一每个单元格的宽度。
修改后代码
// 定义列索引字母 char[] columnLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; final int CELL_WIDTH = 4; // 适配全角字符的固定单元格宽度 // 打印顶部列索引 System.out.print(" "); for (char c : columnLetters) { System.out.printf("%-" + CELL_WIDTH + "c", c); } System.out.println(); // 打印矩阵行 for (int i = 0; i < 7; i++) { // 打印左侧行号(固定2位宽度,右对齐) System.out.printf("%2d ", i + 1); // 打印每行的单元格 for (int j = 0; j < 7; j++) { System.out.printf("%-" + CELL_WIDTH + "s", campo[i][j]); } // 打印右侧行号 System.out.printf("%2d%n", i + 1); } // 打印底部列索引 System.out.print(" "); for (char c : columnLetters) { System.out.printf("%-" + CELL_WIDTH + "c", c); } System.out.println();
关键说明
%-" + CELL_WIDTH + "c:左对齐输出字符,占固定宽度,确保字母和单元格起始位置完全对齐%2d:行号固定占2位宽度,右对齐,保证行号位置统一CELL_WIDTH设为4是因为全角字符占2个半角宽度,预留足够空间避免错位- 用循环生成列索引,彻底避免手动写空格导致的误差
预期输出
A B C D E F G 1 ⛃ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ 1 2 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 2 3 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 3 4 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 4 5 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 5 6 ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ 6 7 ⛁ ⛶ ⛶ ⛶ ⛶ ⛶ ⛃ 7 A B C D E F G
内容的提问来源于stack exchange,提问作者vinc
相关产品推荐
相关产品推荐

