Complete the following static method called repeatString out
Complete the following static method called repeatString (outline below), which returns a String where the String input parameter (element) has been repeated a number of times. For example, if the parameter values are \"stat\" and 4, the return value is\"statstatstatstat\". If times is less than 2, return element directly.
public static String repeatString(String element, int times)
{
//Implement this.
}
Solution
Repeat.java
public class Repeat {
public static void main(String[] args) {
// Calling the method by passing string and no_of_times as parameter
String repeated_String1 =repeatString(\"Stat\", 1);
//Displaying the repeated String
System.out.println(\"Repeated String 1:\"+repeated_String1);
// Calling the method by passing string and no_of_times as parameter
String repeated_String2 =repeatString(\"Stat\", 4);
//Displaying the repeated String
System.out.println(\"Repeated String 2:\"+repeated_String2);
}
/*
* This method will return the appended string
* @Params String,No of times user want to append
* @return String
*/
public static String repeatString(String element, int no_of_times) {
String appended_string = \"\";
// If the no of times is less than 2 return the string as it is
if (no_of_times < 2) {
return element;
}
/*
* If the no of times is more than 2 return the string by appending
* string based on no of times
*/
else {
for (int i = 0; i < no_of_times; i++) {
appended_string += element;
}
}
return appended_string;
}
}
____________________________________
Output:
Repeated String 1:Stat
Repeated String 2:StatStatStatStat
_________________Thank You

