递归 Java 方法

我有一小段代码用于计算某些数字的总和:


public class TestClass {


    public static int sumOfNums(int num[], int int) {   

        if(int == num.length-1) return int; 


        else if( (num[int]%2==0) || num[int] <= 0 ) {

            return num[int] + sumOfNums(num, int+1); }


        else return 0 + sumOfNums(num, int+1);  

    }


    public static void main(String[] args) {

        int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};


        System.out.println(sumOfNums(arr, 0));

    }


}

但是,每当我运行打印语句时,都会出现异常:


Exception in thread "main" java.lang.StackOverflowError

    at TestClass.sumOfNums(TestClass.java:13)

    at TestClass.sumOfNums(TestClass.java:10)

有谁能够帮助我?


陪伴而非守候
浏览 130回答 3
3回答

慕慕森

正如另一位用户所说,您的递归永无止境。更改arr[head-1]为head-1应该在此行上解决此问题:else return 0 + sumNegEven(arr, arr[head-1]);并在这里更改它:return&nbsp;arr[head]&nbsp;+&nbsp;sumNegEven(arr,&nbsp;arr[head-1]);&nbsp;}

狐的传说

public class TestClass {&nbsp; &nbsp; public static int sumNegEven(int arr[], int head) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(head == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; &nbsp; &nbsp; } else if( arr[head]%2==0 || arr[head] <= 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return arr[head] + sumNegEven(arr, head-1);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0 + sumNegEven(arr, head-1);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(sumNegEven(arr, arr.length-1));&nbsp; &nbsp; }}通过调用 arr[head-1] 您调用的是索引的值而不是索引,它们持续很长时间,因为递归没有终止。如果您调用 head-1,您正在调用实际索引,并且将毫无例外地得到答案 21。

海绵宝宝撒

这不会处理数组中的第一项if(head == 0) {&nbsp; &nbsp; &nbsp;return 0;}你必须把它改成if(head < 0) {&nbsp; &nbsp; &nbsp;return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java