1

Expected output array with values : 1, 1

Actual Output get error : "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0"

I'm getting java.lang.ArrayIndexOutOfBoundsException exception and I don't know why. Please Help me out.

Here is my Java file in which, I've problem:

public class Solution {

//compare two arrays and if the value of any element is of a particular index is greater than the other array element, return the value as 1.

    static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2) {

        int[] a = { a0, a1, a2 };
        int[] b = { b0, b1, b2 };
        int[] r = {};
        int y = 1;

        for (int x = 0; x <= a.length; x++) {

            for (int i = 0; i <= a.length; i++) {
                if (a[i] > b[i]) {

                    r[x] = y;

                }
                if (b[i] > a[i]) {

                    System.out.println(r);
                    r[x] = y;

                }
                if (b[i] == a[i]) {

                    System.out.println("");

                }
            }
        }
        return r;
    }

    public static void main(String[] args) throws IOException {

        int[] result = solve(5, 6, 7, 3, 6, 10);

    }
}

Getting an java.lang.ArrayIndexOutOfBoundsException in this code.

Thanks.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39

1 Answers1

1

You use <= as comparison operator. In Java, we always use < to loop over arrays. Replacing your comparison operator in the for-loops should circumvent the ArrayIndexOutOfBoundsException.

Flying Dutchman
  • 135
  • 1
  • 6