public static void getSome(int x) {
int i, j, k, l, m, temp = (x - (x - 1));
for (i = 1; i <= x; i++) {
System.out.print("X");
}
System.out.println();
for (l = 1; l >= (x / 2); l--) {
for (j = 1; j <= l; j++) {
System.out.print(" ");
}
System.out.print("X");
}
for (m = (x - (x + 1)); m >= 1; m--) {
for (k = temp; k <= m; k--) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
}
上面的代码有问题,即使它不是递归功能,你能不能请任何人帮帮我。
答案 0 :(得分:0)
获得此输出
X X
X X
X X
X
X X
X X
X X
使用此功能打印一行
private static void printRow(int width, int level) {
StringBuilder sb = new StringBuilder();
if (width < 1) return;
for (int i = 0; i < level; i++) {
sb.append(" ");
}
for (int i = 0; i < width; i++) {
if (i == 0 || i == width - 1) {
sb.append("X");
}
else {
sb.append(" ");
}
}
System.out.println(sb.toString());
}
这是硬编码的迭代方法
public static void main(String[] args) {
printRow(7, 0);
printRow(5, 1);
printRow(3, 2);
printRow(1, 3);
printRow(3, 2);
printRow(5, 1);
printRow(7, 0);
}
这是递归方法
private static void printX(int width, int level) {
if (width < 2) {
if (width == 1) {
printRow(width, level);
}
return;
}
printRow(width, level);
printX(width - 2, level+1);
printRow(width, level);
}
private static void printX(int width) {
printX(width, 0);
}
public static void main(String[] args) {
printX(7);
}