2

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Econy3
  • 59
  • 1
  • 1
  • 5

5 Answers5

10

If you can use external libraries, StringUtils.repeat sounds perfect for you:

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, _____.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
5

You can print in the same line with System.out.print(" _"); so you can use a loop. print instead of println does not append a new line character.

for (int i=0; i<5; i++){
    System.out.print(" _");
}

Will print: _ _ _ _ _.

Paco Abato
  • 3,920
  • 4
  • 31
  • 54
5

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.generate(() -> " _").limit(5).forEach(System.out::print); // _ _ _ _ _
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
1

With one call to print/println, and using your variable "s":

System.out.println(Stream.generate(() -> " _").limit(s).collect(Collectors.joining()))
Das_Geek
  • 2,775
  • 7
  • 20
  • 26
Robert Field
  • 479
  • 4
  • 5
0

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

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.
Community
  • 1
  • 1
user3871
  • 12,432
  • 33
  • 128
  • 268