This is a beta version of Practice-It. Give us feedback

logo Practice-It logo

repeat

Language/Type: Java recursion recursive programming
Author: Stuart Reges (on 2018/05/01)

Write a method repeat that takes a String s and an integer n as parameters and that returns a String composed of n copies of s. For example:

        repeat("hello", 3) returns "hellohellohello"
        repeat("this is fun", 1) returns "this is fun"
        repeat("wow", 0) returns ""
        repeat("hi ho!", 5) returns "hi ho!hi ho!hi ho!hi ho!hi ho!"

Your method should throw an IllegalArgumentException if passed a negative value for n.

You should solve this problem by concatenating Strings 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 (9 points) will be awarded on the correctness of your solution independent of efficiency. The remaining credit (6 points) will be awarded based on your ability to minimize the number of concatenation operations performed.

You are not allowed to construct any structured objects other than Strings (no array, StringBuilder, ArrayList, etc) and you may not use a while loop, for loop or do/while loop to solve this problem; you must use recursion.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.