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
Print character multiple times
提问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);
s
is the variable.
s
是变量。
采纳答案by Paco Abato
You can print in the same line with System.out.print(" _");
so you canuse a loop. print
instead of println
does 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
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.repeat
sounds perfect for you:
如果您可以使用外部库,StringUtils.repeat
听起来很适合您:
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, _____
.
编辑:
要回答评论中的问题 -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()))