简体   繁体   中英

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. 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). However, you could make use of Arrays.copyOfRange() if you wanted to make your job as easy as possible.

As to your current code, here are some hints:

  1. Why are you always allocating three elements for copy ? The size of the array ought to depend on S1 and S2 .
  2. The arguments to arraycopy() are completely wrong. Read the relevant part of the Java documentation and figure out what the correct values are.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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