3

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:

**** 
1
  • 8
    You can use recursion. Commented Oct 18, 2013 at 17:19

6 Answers 6

12

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

Sign up to request clarification or add additional context in comments.

3 Comments

println prints it on every other line!
I'd prefer a loop instead of recursive call. If n is very big you may get StackOverflowException (or is it Error?)
@Toochka - OPs requirement was to "not" use any explicit loops in the code.
11

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.

1 Comment

5

From the Apache commons common-lang, use StringUtils.repeat:

System.out.println(StringUtils.repeat(q,4)); 

Comments

4

Although it probably loops internally, you could use Guava's Strings avoiding loops in the user code:

System.out.println(Strings.repeat("*", 4)); 

2 Comments

in the background, it uses for-loop too, I guess.
I don't doubt it but useful for avoiding looping in the user code ;)
3

In recursion

printStar(int x) { if(x > 0) { System.out.print("*"); printStar(x-1); } } 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.