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:

****
SheetJS
  • 22,470
  • 12
  • 65
  • 75
NewToJava
  • 59
  • 1
  • 1
  • 9

6 Answers6

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

Rahul
  • 44,383
  • 11
  • 84
  • 103
12

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
5

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

System.out.println(StringUtils.repeat(q,4));
SheetJS
  • 22,470
  • 12
  • 65
  • 75
4

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

System.out.println(Strings.repeat("*", 4));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
3

In recursion

printStar(int x)
{
   if(x > 0)
   {
     System.out.print("*");
     printStar(x-1);
   }
}
Kevin
  • 3,509
  • 4
  • 31
  • 45
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.

mpontillo
  • 13,559
  • 7
  • 62
  • 90