打印一串相似的字符

Printing a string of similar characters

不使用循环,如何打印一系列相似的字符?号码 这些字符将根据我的意愿。 IE。

******(6 颗星)

********(或 8 颗星)

有没有字符串函数可以做到这一点? printf 有什么帮助吗?

您可以使用 recursion 做同样的事情,

printStar(int x)
{
   if(x > 0)
   {
     System.out.print("*");
     printStar(x-1);
   }
}

然后调用printStar(6)打印6次

你可以在这里使用递归。

示例:

public class Test {

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

    public static void printString(int occurance) {
        if(occurance > 0) {
            System.out.print("*");
            printString(--occurance);
        }
    }
}

编辑:如果输入为负,!= 会产生无限循环(即使这样做没有意义)

StringUtils 有如下一些方法 link

Commons Lang StringUtils.repeat()

代码示例如下

String star = "*";
String repeatStar = StringUtils.repeat(star, 6);

另一种可能的解决方案

byte[] bytes = new byte[20];
Arrays.fill(bytes, (byte)'*');
System.out.println(new String(bytes));