簡體   English   中英

如何使用while循環打印“*”n次?

[英]how to print “ * ” n number of times using while loop?

public class Hello {

    public static void pattern() {
        int s1 = 3;

        while(s1 >= 1) {
            System.out.println("*");
            s1--;
        }

    }

    public static void main(String [] args){
        pattern();
    }

}

實際 output:

*
*
*

預期 output:

* * *
 * *
  *

我想使用 while 循環打印“ * ”(如上面預期的輸出)。 我做了一個while循環來控制列數。 我無法進行while循環來控制同一行中output“*”的行3次(下一行2次,依此類推)。

只要你一個循環和一些String.repeat()你就可以畫出你的圖案

  • 重復前導空格,starting 和 0,每輪再重復一個
  • 根據s1重復模式,3 次,然后 2 次,然后 1 次
public static void pattern() {
    int s1 = 3;
    int s2 = 0; // space counter
    while(s1 >= 1) {
        System.out.print(" ".repeat(s2));
        System.out.println("* ".repeat(s1).trim()); // trim to remove last space
        s1--;
        s2++;
    }
}
int lines = 0, asterisks = 3;
String whiteSpace = "";
while (lines++ < 3) {
    System.out.print(whiteSpace);
    for (int i = 0; i < 3; i++) {
        if (i <= (asterisks - lines)) {
            System.out.print("* ");
        }
    }
    whiteSpace += " ";
    System.out.println();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM