不知道如何预防java.lang.StackOverflowError

don't know how to prevent java.lang.StackOverflowError

我应该编写一个递归(!)方法来计算整数数组中给定整数的出现次数,return如果是偶数则为真,如果是奇数则为假。到目前为止,这是我的代码:

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

适用于

evenNumberOf(2, new int[] { 1, 2, 3, 2 });

但它给出 java.lang.WhosebugError

evenNumberOf(1, new int[] { 1, 2, 3, 2 });

我不确定如何防止这种无休止的递归循环,因为我是编程新手,而且这是我第一次使用递归。 提前致谢。

任何递归都应该有一个停止条件和 1 个或多个递归调用。

在这个例子中,停止条件是index >= arr.length所以你开始写函数如下:

public static int counting(int x, int[] arr, int index) {
    if (index >= arr.length) {
        return 0;//there are 0 x's between index and arr.length
    }

处理好停止条件后,剩下的要写:

public static int counting(int x, int[] arr, int index) {
    if (index >= arr.length) {
        return 0;//there are 0 x's between index and arr.length
    }
    int countAfterIndex = counting(x, arr, index+1);//the amount of x's starting from index+1
    if (x == arr[index]) {
        return countAfterIndex + 1;//there is 1 more to add
    } else {
        return countAfterIndex; //the amount of x's after index is the same as the amount from index.
    }
}