java递归取出数组中的元素_java - 使用Java递归在数组中找到正元素的总和 - SO中文参考 - www.soinside.com...

使用Java递归在数组中找到正元素的总和

问题描述 投票:0回答:2

嗨,我只是在学习递归,我试图用Java编写一个递归程序来查找数组中所有正元素的和。使用:这是预期的输出:0 5 7 3 0 17import java.util.Arrays;

public static void main(String[] args) {

int[] list0 = new int[] {};

int[] list1 = new int[] { 5 };

int[] list2 = new int[] { 3, 4 };

int[] list3 = new int[] { -2, 3, -4 };

int[] list4 = new int[] { -1, -2, -4, -5 };

int[] list5 = new int[] { 6, 1, 2, -3, 8 };

}

public static int sumOfPositivesRecursive (int[] a) {

return sumOfPositivesHelper(a, a.length);

}

public static int sumOfPositivesHelper(int[] a, int n) {

if(n == 0) {

return 0;

}

System.out.println(n);

int total = 0;

if(a[n-1] > 0) {

total += a[n-1];

sumOfPositivesHelper(a, n-1);

}

return total;

}

我的输出:0 5 4 0 0 8,似乎只在第一次检查最后一个元素,而不再循环。请帮助我知道我在递归调用中做错了什么。谢谢大家。

java

arrays

recursion

2个回答

1

投票

public static int sumOfPositivesRecursive (int[] a) {

Int i =0

return sumOfPositivesHelper(a, i, 0);

}

public static int sumOfPositivesHelper(int[] a, int i, int sum) {

if(i == a. length) {

return sum;

}

if(a[i] > 0) {

sum+= a[i];

sumOfPositivesHelper(a, i++, sum);

}

}```

Try this sorry it should work but im not sure because at the momento I cant Try it

1

投票

您的代码未正确使用递归,因为总变量未在sumOfPositivesHelper调用之间传递且未正确处理,有效的解决方案将是这样的:package test;

public class Main {

public static void main(String[] args) {

System.out.println(sumOfPositives(new int[] {}));

System.out.println(sumOfPositives(new int[] { 5 }));

System.out.println(sumOfPositives(new int[] { 3, 4 }));

System.out.println(sumOfPositives(new int[] { -2, 3, -4 }));

System.out.println(sumOfPositives(new int[] { -1, -2, -4, -5 }));

System.out.println(sumOfPositives(new int[] { 6, 1, 2, -3, 8 }));

}

private static int sumOfPositives(int[] list) {

return list.length == 0 ? 0 : sumOfPositives(list, 0, 0);

}

private static int sumOfPositives(int[] list, int index, int total) {

if (list[index] > 0) {

total++;

}

if (index + 1 < list.length) {

return sumOfPositives(list, index + 1, total);

}

return total;

}

}

热门问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值