Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive method repeat that accepts a string s and an integer n as para

ID: 3857631 • Letter: W

Question

Write a recursive method repeat that accepts a string s and an integer n as parameters and that returns a String consisting of n copies of s. For example: You should solve this problem by concatenating String objects using the + operator. String concatenation is an expensive operation, so it is best to minimize the number of concatenation operations you perform. For example, for the call repeat ("foo", 500), it would be inefficient to perform 500 different concatenation operations to obtain the result. Most of the credit will be awarded on the correctness of your solution independent of efficiency. The remaining credit will be awarded based on your ability to minimize the number of concatenation operations performed. Your method should throw an IllegalArgumentException if passed any negative value for n. You are not allowed to construct any structured objects other than Strings (no array, List, Scanner, etc.) and you may not use any loops to solve this problem: you must use recursion.

Explanation / Answer

below is the code.. which does repeat sgtring based on recursion. I have used the sample input as string "hello" which you can change accordingly.

public class HelloWorld{

public static String temp = "";
public static void main(String []args) throws IllegalArgumentException{
String s = "hello";
System.out.println(repeat(s,4));
  
}

public static String repeat(String s, int n){
if(n==0){
return temp;
}
  
if(n<0){
throw new IllegalArgumentException();
}
  
temp = temp +s ;
return repeat(s,n-1);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote