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;
}
}