java - 如何递归计算数组中负数的数量(Java)?

标签 java arrays recursion negative-number

我需要使用这个方法:

public static int countNegative(double[] numbers, int count){ }

计算 double 组中负数的数量。如果我可以包含第三个参数 sum,我可以轻松做到这一点,但我只能使用数组和 int。我完全被困住了。我尝试了一些方法,但无法做到正确。我已经得到了从数组大小到 ArrayIndexOutOfBounds 的所有信息,但从未得到正确的答案。谁能帮我解决这个问题吗?

-编辑-

这是确切的分配:

Write a program that reads in a sequence of numbers (not necessary integers) from standard input until 0 is read, and stores them in an array, similar to what you did in assignment 2. This part is done using iteration . You may assume that there will not be more than 100 numbers.

然后计算数组中存储的最大数量,即 负数,并计算正数之和,使用 递归。因此,您将创建递归方法 findMax, 在Assignment9类中countNegative和computeSumPositive,它们 将由 main 方法调用。

具体来说,必须实现以下递归方法 (这些方法不应包含任何循环):

public static double findMax(double[] numbers, int count)  -> It finds the maximum number in the array, count is the number of elements

在数组中

public static int countNegative(double[] 数字, int count) -> 计算负整数

公共(public)静态双computeSumPositive(双[]数字,int计数) -> 对正整数进行求和

findMax() 很简单:

public static double findMax(double[] numbers, int count){
        if(numbers.length - 1 == count)
            return numbers[count];
        else 
            return Math.max(numbers[count], findMax(numbers, count+1));
    }

这是我最近对 ​​countNegative 的尝试。它只返回 99(我用 100 个元素初始化了数组):

public static int countNegative(double[] numbers, int count){
        int i=0;
        if(numbers[count]<0)
            i=1;
        if(numbers.length-1==count)
            return count;
        else
            return i+countNegative(numbers,count+1);
     }

如果我能算出这个负数,我应该就能算出computeSumPositive。

计数可以是您需要的任何值。我在 findMax 中更多地使用它作为索引。

最佳答案

count有什么用?如果它是 index 就有意义了:

public static int countNegative(double[] numbers, int index)
{
    if(index == numbers.length) return 0;
    return (numbers[index] < 0 ? 1 : 0) + countNegative(numbers, index + 1);
}

并这样调用它:

int count = countNegative(array, 0);

关于java - 如何递归计算数组中负数的数量(Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15689097/

相关文章:

java - 在 Java 中加入字符串列表时出现 OutOfMemoryError

java - Pentaho : status 404 error on CentOS

java - 将时间转换为英文单词

arrays - Angular 5绑定(bind)到数组中的特定项目

java - 暴力破解 - StackOverflowError

java - 使用回溯算法排列字符串

python - 删除python中过多的列表

java - 如何在 sonarqube 中为最终类的私有(private)构造函数提供测试覆盖率?

java - 样式文本未从 JTextPane 正确保存

arrays - 带点的网格