二维数组(Java)以循环顺序打印带有字母的三角形
该查询是要编写一个Java方法,该方法根据给定的输入(三角形两侧的字母数)打印以下三角形
public void triangle(int side);
预期产出: 三角形(3)
* * A * *
* F * B *
E * D * C
三角形(4)
* * * A * * *
* * I * B * *
* H * * * C *
G * F * E * D
我提出了一种方法,可以做到这一点,但我用有限的经验编写的代码中有更多的for循环。你们中的任何人都可以查看我的代码,并针对相同的问题提出建议或优化代码吗
public void triangle(int input) {
int x = input;
int y = 2 * input - 1;
int mid = y / 2;
char character = 'A';
String[][] partitionArray1 = new String[x][y];
\\Following for loop will add letters on the side-1
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (i + mid == j) {
partitionArray1[i][j] = "" + character++;
} else {
partitionArray1[i][j] = "*";
}
}
}
\\Following for loop will add letters on the side-2 (horizontal)
for (int j = y - 2; j >= 0; j--) {
j--;
if (j >= 0) {
partitionArray1[x - 1][j] = "" + character++;
} else {
break;
}
}
\\Following for loop will add letters on the side-3
for (int i = x - 2; i >= 0; i--) {
for (int j = 0; j < y; j++) {
if ((i == mid - j) && (j < mid)) {
partitionArray1[i][j] = "" + character++;
}
}
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(partitionArray1[i][j] + "");
}
System.out.println();
}
}
有没有一种算法可以解决这些问题
# 1 楼答案
我很无聊,所以我用了一个数组
# 2 楼答案
尝试:
其思想是将行#
n
与另一行分开打印。行的其余部分正好有两个元素(第一个元素是退化情况除外)相对于中心对称