158k views
5 votes
JAVA

Write a method that takes 2 parameters: a String[] array, and an int numRepeats representing the number of times to repeat each element in the array.

Return a new array with each element repeated numRepeats times.

For example:

repeatElements(new String[]{"hello", "world"}, 3)
Should return a new array with the elements:

["hello", "hello", "hello", "world", "world", "world"]

public String[] repeatElements(String[] array, int numRepeats){
}

User Erdeszt
by
6.9k points

1 Answer

6 votes

Answer:

Answer is in the provided screenshot! This was a lot of fun to make!

Step-by-step explanation:

We need to create a new Array which has to be the size of amount * original - as we now that we are going to have that many elements. Then we just iterate through all the values of the new array and set them equal to each of the elements in order.

Ignore the code in my main function, this was to print to the terminal the working code - as you can see from the output at the bottom!

JAVA Write a method that takes 2 parameters: a String[] array, and an int numRepeats-example-1
User Perishable Dave
by
8.1k points