【问题标题】:don't know how to prevent java.lang.StackOverflowError不知道如何防止 java.lang.StackOverflowError
【发布时间】:2022-01-07 05:52:03
【问题描述】:

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

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.StackOverflowError

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

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

【问题讨论】:

  • 只有在 some 点,函数不需要调用自身时,递归才有效。正如所写,counting总是调用自己。
  • 我同意斯科特的观点;一定有一点,递归函数只是简单地返回一个值,而不是永远依赖于自身的下一次调用。还有一点就是index++++index不一样!您的return counting(x, arr, index++, count++); 行似乎使用它收到的相同参数调用自身,因为n++(后缀)运算符仅在评估后才增加值。我怀疑你喜欢这样称呼它:return counting(x, arr, ++index, ++count);,但return counting(x, arr, index + 1, count + 1); 会更直接。
  • this答案

标签: java recursion stack-overflow


【解决方案1】:

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

在本例中,停止条件为index &gt;= 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.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多