我需要一个完整的金字塔,但我只能得到它的右边。假设看起来像这样,示例输出为 4:
1
212
32123
4321234
我仍然是 java for 循环的新手,所以我尝试进行负增量,但这不起作用,有没有一种方法可以反向打印它?
import java.util.Scanner;
public class Pyramid {
public static void main(String [] args) {
System.out.println("Enter a number 1 to 15");
Scanner input = new Scanner(System.in);
int input1 = input.nextInt();
if (input1 >= 1 && input1 <=15) {
for(int column =1; column <input1; column++) {
for(int row = 1; row < column; row++) {
System.out.print(row + " ");
}
System.out.print(column);
System.out.println();
}
}
}
}
您需要更多循环,并且逐行工作,而不是逐列工作,因此外部循环应使用 row
.
内部循环用于:
- 打印空格
- 打印数字是降序,直到 1(排除(
- 打印数字是从 1 开始的升序
for(int row = 1; row <= input1; row++) {
for(int space = 0; space < input1-row; space++) {
System.out.print(" ");
}
for(int desc = row; desc > 1; desc--) {
System.out.print(desc);
}
for(int asc = 1; asc <= row; asc++) {
System.out.print(asc);
}
System.out.println();
}