Skip to content
Advertisement

How to stop the loop executing n times?

i’m having an issue where I would like the below code to add the specified elements from the first array to the new array at the given indexes. However, the problem is that the loop with not exit.

For eg. The below should print items at index 4 and 5 and then exit as the array only has items indexed up to 5. However it is printing “the”, “mat” followed by “null” and “null”.

Any tips would be appreciated. It has the pass the following tests, which the below advice does not. ”’ @Test public void _2c_pagedData_reflection() throws Exception {

JavaScript

JavaScript

Advertisement

Answer

You are instantiating a array of length maxSize (i.e. 4) even though it is only going to copy 2 elements into that array – so the other 2 elements are null. Calculate the size of the returned array from the array.length and startIndex and then limit this by maxSize. Use System.arrayCopy() to copy arrays.

JavaScript

Edit: adding a sample JUnit test

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement