java显示上下金字塔
我想要这样的输出
5 4 3 2 1 2 3 4 5
4 3 2 1 2 3 4
3 2 1 2 3
2 1 2
1
我怎样才能在左手边留下一个空间
public class Exercise4_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of lines: ");
int num = input.nextInt();
Exercise4_17 exe = new Exercise4_17();
exe.displayPyramid(num);
}
private void displayPyramid(int num) {
for (int i = num; i >= 1; i--) {
for (int space = 1; space <= num - i; ++space) {
System.out.print(" ");
}
for (int k = num; k >= 1; k--) {
System.out.print(k + " ");
}
for (int j = 2; j <= num; j++) {
System.out.print(j + " ");
}
System.out.println();
num--;
}
}
}
我的输出
Enter the number of lines: 5
5 4 3 2 1 2 3 4 5
4 3 2 1 2 3 4
3 2 1 2 3
2 1 2
1
# 1 楼答案
希望这有帮助
参考link
输出: 你想要金字塔里有多少行? 5. 这是你的金字塔
# 2 楼答案
你的代码非常接近。首先,就风格而言,我会对第二个循环使用相同的变量名(
j
是不和谐的,只需使用k
)。第二,也是真正的问题,您正在修改循环中的num
。在循环之前保存初始值,并将其用于空间计算。比如