Java 多次打印字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27322707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:10:21  来源:igfitidea点击:

Print character multiple times

javastringcharacter

提问by Econy3

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);

sis the variable.

s是变量。

采纳答案by Paco Abato

You can print in the same line with System.out.print(" _");so you canuse a loop. printinstead of printlndoes not append a new line character.

您可以在同一行中打印,System.out.print(" _");以便可以使用循环。print而不是println不附加换行符。

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

Will print: _ _ _ _ _.

将打印:_ _ _ _ _

回答by Growler

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

如果在一行代码中...请参阅 Mureinik 的回答

If print "_" in one line:

如果在一行中打印“_”:

Instead:

反而:

Print 1 to 10 without any loop in java

在java中没有任何循环地打印1到10

    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.

回答by Mureinik

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

如果您可以使用外部库,StringUtils.repeat听起来很适合您:

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

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

编辑:
要回答评论中的问题 -StringUtils.repeat需要两个参数 -char您想要重复的次数和您想要的次数,并返回String由该重复组成的。因此,在上面的示例中,它将返回一个由五个下划线组成的字符串_____.

回答by Alexis C.

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 API 来实现这一点。幕后总是有一个迭代,但这是一种可能的实现。

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

回答by Robert Field

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

一次调用print/ println,并使用变量“s”:

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