首页 > 解决方案 > java中带茎的星形图案左帕斯卡箭头

问题描述

    *
   **
  ***
 ******************
*******************
 ******************
  ***
   **
    *

我正在尝试在 Java 中打印此模式。它用于分配,我们必须使用 if,else 语句来打印上述模式。

class fulldesign7
{
    public static void main(String[] args)
    {
        int star=0;
        int space=5;
        for(int i=1;i<=9;i++)
        {
            if(i<=5)
            {
                space--;
                star++;
            }
            else if(i==4||i==5||i==6)
            {
                star=star+10;
            }
            else
            {
                space++;
                star--;
            }
            for(int j=1;j<=space;j++)
            {
                System.out.print(" ");
            }
            for(int k=1;k<=star;k++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

到目前为止,这是我想出的。但是 if 语句和 else 语句发生冲突。

标签: javaif-statement

解决方案


我认为您可以将箭头分为点和尾,我的意思是首先尝试弄清楚如何打印:

    *
   **
  ***
 ****
*****
 ****
  ***
   **
    *

然后在第 3、4 和 5 行为尾巴添加星星

因此,首先创建一个方法来打印给定多个空格和星号的行,如果我们将尾部添加到它:

private static void printLine(int spaces, int stars, boolean addTail) {
    for (int i = 0; i < spaces; i++) {
        System.out.print(" ");
    }
    for (int i = 0; i < stars; i++) {
        System.out.print("*");
    }

    if (addTail) {
        System.out.println("**************");
    } else {
        System.out.println();
    }
}

然后添加星号并删除直到第 5 行的空格,然后为其余行反转。在第 3、4 和 5 行添加尾部:

public static void main(String args[]) {

    int spaces = 5;
    int stars = 0;

    for (int line = 0; line < 9; line++) {
        if (line<5) {
            spaces --;
            stars ++;
        } else {
            spaces ++;
            stars --;
        }

        boolean addTail = line >= 3 && line <=5;

        printLine(spaces, stars, addTail);
    }

}

注意:您也可以尝试变得更聪明,并注意两件事:

  • 空格数是 (line - 4) 的绝对值
  • 星数总是 5 减去空格数

所以main也可以这样写:

public static void main(String args[]) {

    for (int line = 0; line < 9; line++) {
        int spaces = Math.abs(line - 4);
        boolean addTail = line >= 3 && line <=5;
        printLine(spaces, 5-spaces, addTail);
    }
}

推荐阅读