Java递归判断数组元素出现次数奇偶报StackOverflowError如何解决
代码问题原因与修复方案
核心问题点
- 缺失递归终止条件:
counting方法没有设置递归结束的出口,当下标超出数组范围后仍会继续递归,最终触发栈溢出。 - 下标判断顺序错误:现有代码先访问
arr[index]再判断index < arr.length,一旦下标越界会先触发数组越界异常,合法性判断完全不生效。 - 后自增逻辑错误:
index++、count++属于后自增,传参时会传入自增前的原值,导致每次递归的下标永远停留在初始值,递归无法向下推进,进入无限循环。
修正后的代码
public static boolean evenNumberOf(int x, int[] arr) { // 空数组时元素出现次数为0,0是偶数,返回true if (arr == null || arr.length == 0) return true; 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 (index >= arr.length) { return count; } // 先判断下标合法,再访问元素 if (arr[index] == x) { count++; } // 直接传入+1后的值,推进递归 return counting(x, arr, index + 1, count); }
验证效果
- 调用
evenNumberOf(2, new int[] { 1, 2, 3, 2 }):元素2出现2次,输出true并返回true - 调用
evenNumberOf(1, new int[] { 1, 2, 3, 2 }):元素1出现1次,输出false并返回false
内容的提问来源于stack exchange,提问作者egg
相关产品推荐
相关产品推荐

