0

Im trying to split an array, store one part in one array and the other part in another array. Then im trying to flip the 2 and store them in a new array. here is what i have

public int[] flipArray(){
        int value = 3;
        int[] temp1 = new int[value];
        int[] temp2 = new int[(a1.length-1) - (value+1)];
        int[] flipped = new int[temp1.length+temp2.length];

    System.arraycopy(a1, 0, temp1, 0, value);
    System.arraycopy(a1, value+1, temp2, 0, a1.length-1);
    System.arraycopy(temp2, 0, flipped, 0, temp2.length);
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
            return flipped;
    }
    private int[]a1={1,2,3,4,5,6,7,8,9,10};
2

4 Answers 4

1

You get the ArrayIndexOutOfBoundsException when you want to access an array element outside the range [0, length - 1];

You can find the probelm yourself, if you either use the debugger, or place a System.out.println(text) before each call of System.arraycopy where you output the array length of the source and destination array and the number of elements to copy

Sign up to request clarification or add additional context in comments.

Comments

0

Your indexing and array lengths are off:

public int[] flipArray(){
    int value = 3;
    int[] temp1 = new int[value];
    int[] temp2 = new int[a1.length - value];
    int[] flipped = new int[a1.length];

    System.arraycopy(a1, 0, temp1, 0, value);
    System.arraycopy(a1, value, temp2, 0, temp2.length);
    System.arraycopy(temp2, 0, flipped, 0, temp2.length);
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
    return flipped;
}
private int[]a1={1,2,3,4,5,6,7,8,9,10};

The key is to understand that System.arraycopy does not copy the element at the last index.

Comments

0

get rid of unnecessary manipulations with indexes:

public int[] flipArray(){
int value = 3;
int[] temp1 = new int[value];
int[] temp2 = new int[a1.length - value];
int[] flipped = new int[temp1.length+temp2.length];

System.arraycopy(a1, 0, temp1, 0, value);
System.arraycopy(a1, value, temp2, 0, temp2.length);
System.arraycopy(temp2, 0, flipped, 0, temp2.length);
System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
}

Comments

0

This line is wrong:

System.arraycopy(a1, value+1, temp2, 0, a1.length-1);

You start from position 4 and want to copy 9 elements. That means it tries to copy elements from index 4 to 12 in the array.

Comments

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.