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.
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.
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, _____
.
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: _ _ _ _ _
.
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); // _ _ _ _ _
With one call to print
/println
, and using your variable "s":
System.out.println(Stream.generate(() -> " _").limit(s).collect(Collectors.joining()))
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.