2

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;

        }

}
1
  • why would it stop printing? just because you stop adding elements, doesn't mean your array size gets limited Commented Dec 1, 2021 at 11:17

2 Answers 2

1

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting a "java reached end of file while parsing" error when trying to use the list code?
Are there any brackets not closed? In my code I have removed the if statement, They might be some left
0

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);
}

3 Comments

I have edited the original post as the above does not pass the required tests.
@ItchyPrune I added a simple JUnit test that passes with my code (and should pass with Beri's answer as well). Your test is appears to be invoking the method via reflection which is unnecessary and may be flawed. Does it give you any feedback when it fails? Is tester a custom class? Does your class have more than one method with the named pagedData?
Hi, I hadn't got as far as using the system class with arraycopy in my learning but it is a much more efficient way of doing it, thank you!. It wasn't working originally as the arraycopy was case sensitive and the copy had an uppercase C. I've looked into the arraycopy method and it is exactly what i need. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.