How do you print a diamond pattern in Java?

Here is a Java program code that can print out a diamond pattern.

public class Main {
    public static void main(String[] args) {
        int n = 5; // 菱形的行数

        for (int i = 1; i <= n; i++) {
            for (int j = i; j < n; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        for (int i = n - 1; i > 0; i--) {
            for (int j = n; j > i; j--) {
                System.out.print(" ");
            }
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

In the code above, we initially define the number of rows of the diamond as 5. Then, we use two nested for loops to print the diamond pattern, first printing the top half of the diamond, and then printing the bottom half. The number of diamonds in each row is 2i-1, where i is the current row number. Finally, run the program to see the printed diamond pattern.

bannerAds