Java 打印字符串 'X' 次(无循环)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19455473/
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 a String 'X' Times (No Loop)
提问by NewToJava
Is it possible to print a string 'x' times?
是否可以打印字符串“x”次?
For example if given the string
例如,如果给定字符串
String q = "*";
Let's say the user entered the number '4' for the amount of times that they wanted the string repeated.
假设用户输入数字“4”表示他们希望字符串重复的次数。
The program would print:
该程序将打印:
****
采纳答案by SudoRahul
You can use recursion like this
你可以像这样使用递归
private void printStar(int n){
if(n > 0){
System.out.print("*");
printStar(n-1);
}
}
And call the method like this initially - printStar(4);
并最初调用这样的方法 - printStar(4);
回答by Reimeus
回答by Kevin
In recursion
在递归中
printStar(int x)
{
if(x > 0)
{
System.out.print("*");
printStar(x-1);
}
}
回答by Rohit Jain
You can make use of a char[]
array of given length to build a String
, then replace each character with *
:
您可以使用char[]
给定长度的数组来构建一个String
,然后将每个字符替换为*
:
String repeatedStar = new String(new char[4]).replace('public static void printNX(int n)
{
char[] c = new char[n];
Arrays.fill(c, 'x');
System.out.println(new String(c));
}
', '*');
Well, that would use a loop internally though.
好吧,这将在内部使用循环。
回答by mpontillo
I know the point is probably to use recursion, but recursion in this case is a horrible solution. Here's a solution that is more efficient (though it very likely uses a loop in Arrays.fill
!)
我知道重点可能是使用递归,但在这种情况下递归是一个可怕的解决方案。这是一个更有效的解决方案(尽管它很可能在Arrays.fill
!)
System.out.println(StringUtils.repeat(q,4));
Of course, it's possible that Arrays.fill
is calls into native code which is optimized to use an efficient instruction for filling the array and avoids a loop. But you never know.
当然,有可能Arrays.fill
调用本机代码,该代码经过优化以使用有效的指令来填充数组并避免循环。但你永远不知道。
I don't necessarily agree that using recursion "isn't looping"; all this is doing is thrashing the stack; the the CPU will still technically loop by continually jumping back to the top of the recursive function.
我不一定同意使用递归“不是循环”;所有这些都在颠簸堆栈;从技术上讲,CPU 仍然会通过不断跳回到递归函数的顶部来循环。
回答by SheetJS
From the Apache commons common-lang, use StringUtils.repeat
:
从Apache commons common-lang,使用StringUtils.repeat
: