I am supposed to write a recursive(!) method to count the amount of occurrences of a given integer in an integer array and return true if even and false if odd. This is my code so far:
public static boolean evenNumberOf(int x, int[] arr) {
if (arr == null || arr.length == 0)
return false;
int count = counting(x, arr, 0, 0);
if (count % 2 == 0) {
System.out.print("true");
return true;
} else {
System.out.print("false");
return false;
}
}
public static int counting(int x, int[] arr, int index, int count) {
if (arr[index] == x && index < arr.length) {
return counting(x, arr, index++, count++);
} else {
return counting(x, arr, index++, count);
}
}
It works for
evenNumberOf(2, new int[] { 1, 2, 3, 2 });
but it gives java.lang.StackOverflowError
for
evenNumberOf(1, new int[] { 1, 2, 3, 2 });
I am not sure how to prevent this endless recursive loop, as I'm new to programming and it's my first time using recursion. Thanks in advance.