In this section, you will learn how to repeat string without using for loops.
The given example accepts the number of times and iterates the string to the number of times set by the user without using while loop or any other control statements.
Example:
import java.util.*;
class RepeatString
{
public static String repeat(String str, int times){
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter no. of times: ");
int no=input.nextInt();
String st="Hello World";
System.out.println(repeat(st+"\n", no));
}
}
Output:
Enter no. of times: 5 Hello World Hello World Hello World Hello World Hello World
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.