Java

java打印菱形的代码怎么写

小亿
111
2024-01-27 19:05:47
栏目: 编程语言

以下是一个打印菱形的Java代码示例:

import java.util.Scanner;

public class DiamondPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入菱形的行数:");
        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;
        }
    }
}

运行程序后,会提示输入菱形的行数,输入后即可打印出对应行数的菱形图案。

0
看了该问题的人还看了