简体   繁体   English

如何让数组方法为我提供正确的输出?

[英]How do I get the array method to give me the correct output?

I'm trying to make a method that expects an array of int and two int S1 and int S2 as parameters. 我正在尝试创建一个期望int数组和两个int S1int S2作为参数的方法。 The integers represent the starting position and the ending position of a subarray within the parameter array. 整数表示参数数组中子数组的起始位置和结束位置。 The method returns a new array that contains the elements from the starting position to the ending position. 该方法返回一个新数组,其中包含从起始位置到结束位置的元素。

This is what I have, but it keeps giving me this message: 这就是我所拥有的,但它不断给我这样的信息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
    at java.lang.System.arraycopy(Native Method)
    at testing.subArray(testing.java:14)
    at testing.main(testing.java:9)

Here's the code: 这是代码:

public class testing{

public static void main(String args[])
{
int[] firstArray = {8,9,10,11,12,13};
subArray(firstArray, 2, 4);
}

public static void subArray(int[]originalArray, int S1, int S2)
{
int[] copy = new int[3];
System.arraycopy(originalArray, S1, copy, S2, 2);

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

}

Help please! 请帮助! :) :)

The method returns a new array that contains the elements from the starting position to the ending position. 该方法返回一个新数组,其中包含从起始位置到结束位置的元素。

At present it doesn't return anything (it's a void method). 目前它不会返回任何东西(这是一种void方法)。 However, you could make use of Arrays.copyOfRange() if you wanted to make your job as easy as possible. 但是,如果您希望尽可能Arrays.copyOfRange() ,可以使用Arrays.copyOfRange()

As to your current code, here are some hints: 至于您当前的代码,这里有一些提示:

  1. Why are you always allocating three elements for copy ? 为什么总是为copy分配三个元素? The size of the array ought to depend on S1 and S2 . 数组的大小应该取决于S1S2
  2. The arguments to arraycopy() are completely wrong. arraycopy()的参数完全错误。 Read the relevant part of the Java documentation and figure out what the correct values are. 阅读Java文档的相关部分,找出正确的值。

You'll find that this works much better: 你会发现这效果更好:

public class testing {

    public static final int DEFAULT_LENGTH = 3;

    public static void main(String args[]) {
        int[] firstArray = {8, 9, 10, 11, 12, 13};
        int [] subArray = createSubArray(firstArray, 2, 4);
        for (int i = 0; i < subArray.length; i++) {
            System.out.println(subArray[i]);
        }
    }

    public static int [] createSubArray(int[] originalArray, int startPosition1, int valuesToCopy) {
        int subArrayLength = Math.min((originalArray.length-startPosition1), valuesToCopy);
        int [] subArray = new int[subArrayLength];
        System.arraycopy(originalArray, startPosition1, subArray, 0, subArrayLength);

        return subArray;
    }

}

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

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