0

I'm starting with java and I just want to print an array but I don't know why I'm getting this error:

java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6

This is my code:

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6};
        int[] output = Main.cloneEvenNumbers(arr);
        System.out.println(Arrays.toString(output));
    }

    public static int[] cloneEvenNumbers(int[] a) {
        if (a == null || a.length == 0) {
            return a;
        }
        int end = a.length, i = getLastNumber(a);
        while (i >= 0) {
            if (a[i] % 2 == 0) {
                a[--end] = a[i];
            }
            a[--end] = a[i];
            i--;
        }
        return a;
    }

    public static int getLastNumber(int[] a) {
        int i = a.length - 1;
        while (i >= 0 && a[i] == -1) {
            i--;
        }
        return i;
    }
}
azro
  • 53,056
  • 7
  • 34
  • 70
alex
  • 335
  • 6
  • 17
  • Did you check the line ? The error is not on printing (printing is even not your method) it's when you build you array – azro Feb 06 '20 at 20:56
  • You are decrementing `end` twice and `i` only once. `end` reaches 0 before `i` and thus the exception. – Harshal Parekh Feb 06 '20 at 20:57
  • I recommend doing some research into some basic tutorials about using a debugger. You will learn very slowly if every time you have a slight hiccup you resort to asking a question online. – Harshal Parekh Feb 06 '20 at 20:58
  • 1
    ok now I see the --end that cause the error @HarshalParekh thnks – alex Feb 06 '20 at 21:26

0 Answers0