Is it possible to print a string 'x' times?
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.
The program would print:
****
Is it possible to print a string 'x' times?
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.
The program would print:
****
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);
You can make use of a char[]
array of given length to build a String
, then replace each character with *
:
String repeatedStar = new String(new char[4]).replace('\0', '*');
Well, that would use a loop internally though.
From the Apache commons common-lang, use StringUtils.repeat
:
System.out.println(StringUtils.repeat(q,4));
In recursion
printStar(int x)
{
if(x > 0)
{
System.out.print("*");
printStar(x-1);
}
}
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
!)
public static void printNX(int n)
{
char[] c = new char[n];
Arrays.fill(c, 'x');
System.out.println(new String(c));
}
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.
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.