简体   繁体   English

如何停止循环执行n次?

[英]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".下面应该打印索引 4 和 5 处的项目,然后退出,因为数组只有索引到 5 的项目。但是它打印“the”,“mat”,后跟“null”和“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 { ''' @Test public void _2c_pagedData_reflection() 抛出异常 {

    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;

        }

}

You are creating an empty array size of 4, and you want to copy only 2 last values from input value.您正在创建一个大小为 4 的空数组,并且您只想从输入值中复制 2 个最后一个值。 So the last two values are null.所以最后两个值是 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.您可以使用 List 而不是数组,这样您就可以完全跳过这个问题。 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"]

You are instantiating a array of length maxSize (ie 4) even though it is only going to copy 2 elements into that array - so the other 2 elements are null.您正在实例化一个长度为maxSize (即 4)的数组,即使它只会将 2 个元素复制到该数组中 - 所以其他 2 个元素是 null。 Calculate the size of the returned array from the array.length and startIndex and then limit this by maxSize .array.lengthstartIndex计算返回数组的大小,然后通过maxSize对其进行限制。 Use System.arrayCopy() to copy arrays.使用System.arrayCopy()复制 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编辑:添加示例 JUnit 测试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM