[英]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()
你就可以畫出你的圖案
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.