2 回答
TA贡献1785条经验 获得超4个赞
经过一些实验,这可以工作:
public static void printBox(int rows, int columns) {
int sumOfColumns = 2 * columns + rows - 1;
int sumOfRow = 2 * columns + 2 * rows - 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
if (i == 1) {
System.out.printf(String.format("%3d", j));
} else if (j == 1) {
System.out.printf(String.format("%3d", sumOfRow - (i + j - 1)));
} else if (j == columns) {
System.out.printf(String.format("%3d", i + j - 1));
} else if (i == rows) {
System.out.printf(String.format("%3d", sumOfColumns - j));
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
System.out.print("\n");
}
测试用例:
public static void main(String[] args) {
printBox(3, 3);
printBox(4, 4);
printBox(3, 4);
}
结果:
1 2 3
8 4
7 6 5
1 2 3 4
12 5
11 6
10 9 8 7
1 2 3 4
10 5
9 8 7 6
添加回答
举报