Java - Number Pyramid - Code

Here is an example code for a number pyramid written in Java:

import java.util.Scanner;

public class NumberPyramid {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);

        System.out.print("请输入金字塔的行数:");
        int rows = input.nextInt();

        for (int i = 1; i <= rows; i++) {
    
    
            // 打印空格
            for (int j = 1; j <= rows - i; j++) {
    
    
                System.out.print(" ");
            }

            // 打印数字
            for (int k = 1; k <= i; k++) {
    
    
                System.out.print(k + " ");
            }

            // 打印数字(逆序)
            for (int k = i - 1; k >= 1; k--) {
    
    
                System.out.print(k + " ");
            }

            System.out.println();
        }
    }
}

This code will first ask the user to enter the number of rows in the pyramid, and then use a nested loop to print out the pyramid of numbers. Each line will print the corresponding number of numbers according to the number of lines, aligned with spaces. Numbers are printed in order from 1 to the row number and then back to 1. After executing the code, you will see a sequence of numbers arranged in a pyramid shape. You can adjust the code yourself as needed.

Guess you like

Origin blog.csdn.net/wzxue1984/article/details/132983948