Print character multiple times

心已入冬 提交于 2020-04-07 08:49:06

问题


How can I print a character multiple times in a single line? This means I cannot use a loop.

I'm trying to print " _" multiple times.

I tried this method but it's not working:

System.out.println (" _" , s);

s is the variable.


回答1:


You can print in the same line with System.out.print(" _"); so you can use a loop. print instead of println does not append a new line character.

for (int i=0; i<5; i++){
    System.out.print(" _");
}

Will print: _ _ _ _ _.




回答2:


If you can use external libraries, StringUtils.repeat sounds perfect for you:

int s = 5;
System.out.println(StringUtils.repeat('_', s));

EDIT:
To answer the question in the comments - StringUtils.repeat takes two parameters - the char you want to repeat and the number of times you want it, and returns a String composed of that repetition. So, in the example above, it will return a string of five underscores, _____.




回答3:


You can use the new Stream API to achieve that. There always be an iteration behind the scenes, but this is one possible implementation.

Stream.generate(() -> " _").limit(5).forEach(System.out::print); // _ _ _ _ _



回答4:


With one call to print/println, and using your variable "s":

System.out.println(Stream.generate(() -> " _").limit(s).collect(Collectors.joining()))



回答5:


There isn't a shortcut like what you've posted...

And what do you mean "In a single line"?

If in one line of code... see Mureinik's answer

If print "_" in one line:

Instead:

Print 1 to 10 without any loop in java

    System.out.print("_");
    System.out.print("_");
    System.out.print("_");
    System.out.print("_");
    System.out.print("_");

Or

public void recursiveMe(int n) {
    if(n <= 5) {// 5 is the max limit
        System.out.print("_");//print n
        recursiveMe(n+1);//call recursiveMe with n=n+1
    }
}
recursiveMe(1); // call the function with 1.


来源:https://stackoverflow.com/questions/27322707/print-character-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!