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! 🙂
At present it doesn’t return anything (it’s a
voidmethod). However, you could make use ofArrays.copyOfRange()if you wanted to make your job as easy as possible.As to your current code, here are some hints:
copy? The size of the array ought to depend onS1andS2.arraycopy()are completely wrong. Read the relevant part of the Java documentation and figure out what the correct values are.