溫馨提示×

java打印菱形的代碼怎么寫

小億
107
2024-01-27 19:05:47
欄目: 編程語言

以下是一個(gè)打印菱形的Java代碼示例:

import java.util.Scanner;

public class DiamondPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("請輸入菱形的行數(shù):");
        int rows = scanner.nextInt();

        int spaces = rows - 1;
        int stars = 1;

        // 打印上半部分
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= stars; j++) {
                System.out.print("*");
            }
            System.out.println();
            spaces--;
            stars += 2;
        }

        // 打印下半部分
        spaces = 1;
        stars = rows * 2 - 3;
        for (int i = 1; i <= rows - 1; i++) {
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= stars; j++) {
                System.out.print("*");
            }
            System.out.println();
            spaces++;
            stars -= 2;
        }
    }
}

運(yùn)行程序后,會(huì)提示輸入菱形的行數(shù),輸入后即可打印出對應(yīng)行數(shù)的菱形圖案。

0