ItchyPrune
ItchyPrune

Reputation: 33

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 {

    String[] data = {"the", "cat", "sat", "on", "the", "mat"};

    {
        final String[] expected2n2 = {"sat", "on"};
        final String[] result = tester.executeStatic(String[].class, "pagedData", data, 2, 2);
        assertArrayEquals(expected2n2, result);
    }
    {
        final String[] expected4n4 = {"the", "mat"};
        final String[] result = tester.executeStatic(String[].class, "pagedData", data, 4, 4);
        assertArrayEquals(expected4n4, result);
    }
    {
        final String[] expected2n3 = {"sat", "on", "the"};
        final String[] result = tester.executeStatic(String[].class, "pagedData", data, 2, 3);
        assertArrayEquals(expected2n3, result);
    }
}'''

'

package com.company;

public class Main {

    public static void main(String[] args) {
        String[] data = {"the", "cat", "sat", "on", "the", "mat"};

        String[] lol = pagedData(data, 4, 4);

        for (int i = 0; i < lol.length; i++) {
            System.out.println(lol[i]);
        }

    }

    static String[] pagedData(String[] array, int startIndex, int maxSize) {

        String[] newArray = new String[maxSize];
        int count = 1;

            for (int i = 0; i < newArray.length; i++) {
                
                if (startIndex < array.length) {

                String index = array[startIndex];
                newArray[i] = index;
                startIndex++;
                count++;
            }
        }
        return newArray;

        }

}

Upvotes: 2

Views: 76

Answers (2)

vsfDawg
vsfDawg

Reputation: 1527

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.

static String[] pagedData(String[] array, int startIndex, int maxSize) {
  int length = array.length - startIndex;
  if (length > maxSize) {
    length = maxSize;
  }
  String[] slice = new String[length];
  System.arrayCopy(array, startIndex, slice, 0, length);
  return slice;
}

Edit: adding a sample JUnit test

@Test public void testSlice() {
  String[] array = {"the","cat","sat","on","the","mat"};
  int startIndex = 4;
  int maxSize = 4;
  String[] expected = {"the","mat"};

  String[] actual  = Testing.pagedData(array, startIndex, maxSize);

  Assert.assertArrayEquals(expected, actual);
}

Upvotes: 0

Beri
Beri

Reputation: 11610

You are creating an empty array size of 4, and you want to copy only 2 last values from input value. So the last two values are null.

static String[] pagedData(String[] array, int startIndex, int maxSize) {
    if(array.length - maxSize<1){ // edge case
       return new String[0];
    }
    String[] newArray = new String[array.length - maxSize];

    ...
    return newArray;

}

You could use a List instead of an array, this way you could skip this problem totally. Secondly converting from a list to an array is straight

static String[] pagedData(String[] array, int startIndex, int maxSize) {
    int counter = 0;
    List<String> results = new ArrayList<>();
    for (int i = startIndex; i < array.length && counter <= maxSize; i++) {
         String index = array[startIndex];
         results.add(index); 
         counter ++;
    }
    return results.toArray(new String[0]);
}

The result:

["the", "mat"]

Upvotes: 1

Related Questions