如何打印"* "使用while循环n次? [英] how to print " * " n number of times using while loop?
本文介绍了如何打印"* "使用while循环n次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Hello {
public static void pattern() {
int s1 = 3;
while(s1 >= 1) {
System.out.println("*");
s1--;
}
}
public static void main(String [] args){
pattern();
}
}
实际输出:
*
*
*
预期输出:
* * *
* *
*
我想使用 while 循环打印"* "(如上面预期的输出).我做了一个控制列数的while循环.我无法进行 while 循环来控制行在同一行中输出 "*" 3 次(下一行 2 次,依此类推).
I would like to print " * " (like the above-expected output) using while loop. I made a while loop controlling the number of columns. I'm not able to make a while loop to control the rows to output "*" in the same line 3 times (next line 2 times and so on).
推荐答案
只需要一个循环和一些 String.repeat()
你就可以画出你的图案
With just you one loop and some String.repeat()
you can draw your pattern
- 重复前导空格,开始和0,每轮多一次
- 根据 ong
s1
重复模式,3 次,然后 2 次,然后 1 次
- Repeat the leading space, starting and 0, and one more each round
- Repeat the pattern depending ong
s1
, 3 times, then 2 then 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++;
}
}
这篇关于如何打印"* "使用while循环n次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文