需求:编写程序,提示用户输入一个整数,然后显示一个金字塔形状的图案,图形如下所示:
1
2 1 2
3 2 1 2 3
不多废话直接上代码:
Scanner input = new Scanner(System.in);
System.out.print("input a number:");
int n = input.nextInt();
int countFront = 1;
for (int i = 1; i <= n; i++) {
int out = i;
for (int j = 1; j <= 2 * n - 1; j++) {
if (countFront <= n - i || countFront >= n + i) {
System.out.print(" ");
} else {
if (j <= n) {
System.out.printf("%2d", out);
System.out.print(" ");
out--;
}
if (j > n) {
System.out.printf("%2d", out + 2);
System.out.print(" ");
out++;
}
}
countFront++;
}
countFront = 1;
System.out.println();
}