0

I'm studying Algorithms and I have a problem with my code, it gaves me a an IndexOutOfBound exception but I don't know why. Can you please help me?

This is my code:

public static void main(String[] args) {

    int[] A = { 2, 5, 3, 4, 2, 5, 3, 2, 4, 8, 7, 4, 3 };
    int[] B = { 8, 6, 1, 5, 2, 1, 7, 9, 8, 3, 5, 2 };

    intersection(A,B);


}

public static int[] intersection(int[] A, int[] B) {

    Arrays.sort(A);
    Arrays.sort(B);

    int[] finalArray = new int[12];

    int counter = 0;

    for(int i = 0; i <= A.length; i++) {
        for(int x = 0; x <= B.length; x++) {
            if(B[x] == A[i]) {
                finalArray[counter] = B[x];
                counter++;
            }
        }
    }

    for(int s : finalArray) {
        System.out.println(s);
    }

    return null;
}

The error is found at line 27.

Thanks in advance :)

Simone C.
  • 369
  • 4
  • 14

0 Answers0