如果我正确理解了这个问题,我会提出这个解决方案:
- 从概念上讲,您需要两个函数:
- 一个初始化地板和天花板
---------------
static void initialiseCeilingAndFloor(char plane[][], int n) {
for (int i = 0; i < plane.length; i++) {
plane[0][i] = '-'; // ceiling is initialised
plane[plane.length - 1][i] = '-'; //floor is initialised
}
}
另一个在每面墙上画一条线|. . . . . . . . .|。
为了清楚起见,我实际上将这个方法一分为二:InitialiseInternalRow 执行它所说的,InitialiseBody 用它来初始化整个飞机体
static void initialiseBody(char plane[][]) {
// we already initialised floor and ceiling, so here we'll
for (int i = 1; i < plane.length - 1; i++) {
// reduce the cycle at the internal lines
initialiseInternalRow(plane, i);
}
}
static void initialiseInternalRow(char plane[][], int i) {
for (int j = 0; j < plane.length; j++) {
// if we are at the extremes, we draw a wall: '|'
if (j == 0 || j == plane.length - 1)
plane[i][j] = '|';
else // otherwise we leave space
plane[i][j] = ' ';
}
}
这样您就可以轻松地在main 中初始化您的数组:
char plane[][] = new char[n][n];
initialiseCeilingAndFloor(plane);
initialiseBody(plane);
您甚至可以考虑将这两种方法包装在一起,一键初始化事物,如下所示:
static void initialisePlane(char plane[][]) {
initialiseCeilingAndFloor(plane);
initialiseBody(plane);
}
这样你就可以轻松地从你的 main 调用:
char plane[][] = new char[n][n];
initialisePlane(plane);
如果您的终端更多地将输出显示为矩形,请不要担心。这取决于您用于显示文本的特定应用程序所使用的格式。只需用点替换空格,然后计算它们。
在这里进行严格的测试。