蝴蝶图案输出

问题描述 投票:0回答:2
public class butterflypattern {
    
    public static void Pattern(int n){
        for(int i=1; i<=n; i++){
            for(int j=1; j<=i; j++){
                System.out.print("* ");
            }
            for(int j=1; j<=2*(n-i); j++){
                System.out.print(" ");
            }
            for(int j=1; j<=i; j++){
                System.out.print("* ");
            }
            System.out.println();
        }
        for(int i=n; i>=1; i--){
            for(int j=1; j<=i; j++){
                System.out.print("* ");
            }
            for(int j=1; j<=2*(n-i); j++){
                System.out.print(" ");
            }
            for(int j=1; j<=i; j++){
                System.out.print("* ");
            }
            System.out.println();
        }
        
    }
    public static void main(String[] args) {
        Pattern(5);
    }
}

我必须使用星号 (*) 打印蝴蝶图案,但我得到的输出与预期相同。这是我的逻辑,代码输出图像如下。

This is the output with this code

Expected

java coding-style
2个回答
0
投票

您缺少空格,请将

2*
替换为
4*

您还可以使用

String.repeat

获得更简单的代码
public static void pattern(int n) {
    String stars;
    for (int i = 1; i <= n; i++) {
        stars = "* ".repeat(i);
        System.out.println(stars + " ".repeat(4 * (n - i)) + stars);
    }
    for (int i = n; i >= 1; i--) {
        stars = "* ".repeat(i);
        System.out.println(stars + " ".repeat(4 * (n - i)) + stars);
    }
}

0
投票

这是一个例子。

String create(int n, char c) {
    StringBuilder a = new StringBuilder(), b;
    String s = String.valueOf(c), d = System.lineSeparator();
    int i;
    for (i = 1; i <= n; i++) {
        b = new StringBuilder();
        b.append(s.repeat(i * 2));
        b.insert(i, " ".repeat((n - i) * 2));
        b.append(d);
        a.append(b);
    }
    for (i = n - 1; i >= 1; i--) {
        b = new StringBuilder();
        b.append(s.repeat(i * 2));
        b.insert(i, " ".repeat((n - i) * 2));
        b.append(d);
        a.append(b);
    }
    return a.toString();
}

输出

*        *
**      **
***    ***
****  ****
**********
****  ****
***    ***
**      **
*        *
&            &
&&          &&
&&&        &&&
&&&&      &&&&
&&&&&    &&&&&
&&&&&&  &&&&&&
&&&&&&&&&&&&&&
&&&&&&  &&&&&&
&&&&&    &&&&&
&&&&      &&&&
&&&        &&&
&&          &&
&            &
© www.soinside.com 2019 - 2024. All rights reserved.