【发布时间】: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