Java 加正数的递归数组

Java 加正数的递归数组,java,arrays,recursion,Java,Arrays,Recursion,我有一个接受数字的数组。我的方法之一是计算数组中的正数。因此,如果他们输入2 3 4 5 6和0来终止程序。它应该输入打印出的正数:5,但它会打印出正数:4。它错过了最后一个号码。但是,如果我执行23445-1400{0终止},它会打印出正确的正数,在本例中是5。我做了一些调试,但似乎无法解决它。有什么帮助吗 public static int countPositive(int[] numbers, int startIndex, int endIndex) { if (star

我有一个接受数字的数组。我的方法之一是计算数组中的正数。因此,如果他们输入2 3 4 5 6和0来终止程序。它应该输入打印出的正数:5,但它会打印出正数:4。它错过了最后一个号码。但是,如果我执行23445-1400{0终止},它会打印出正确的正数,在本例中是5。我做了一些调试,但似乎无法解决它。有什么帮助吗

public static int countPositive(int[] numbers, int startIndex, int endIndex)
{   
    if (startIndex == endIndex) 
    {   
        if (numbers[startIndex] > 0)        
        {   
            return 1;
        }   
        else
            return 0;      
    }   
    else
    {       
        if (numbers[startIndex] > 0)        
        {       
            return 1 + countPositive(numbers, startIndex +1, endIndex); 
        }
        else        
            return countPositive(numbers, startIndex +1, endIndex);     
    }
}

要粘贴所有代码,请首先粘贴整个代码:

public class JavaApplication5 {

    public static int countPositive(int[] numbers, int startIndex, int endIndex)
{   
    if (startIndex == endIndex) 
    {   
        if (numbers[startIndex] > 0)        
        {   
            return 1;
        }   
        else
            return 0;      
    }   
    else
    {       
        if (numbers[startIndex] > 0)        
        {       
            return 1 + countPositive(numbers, startIndex +1, endIndex); 
        }
        else        
            return countPositive(numbers, startIndex +1, endIndex);     
    }
}
    public static void main(String[] args) {

        int i=countPositive(new int[] { -3, 30, 40, 55, 62}, 0, 4);
        System.out.println(i);
    }
}
此代码返回4个正数:30,40,55,62。
您可以使用数组、strt和结束索引。

int i=countPositive(new int[] { -3, 30, 40, 55, 62,-3, 43}, 0, 6);
上面的代码给我返回了5个正数

int i=countPositive(new int[] { -3, 30, 40, 55, 62,-3, 43}, 3, 6);
给我返回了3个正数:从55,62,-3和43它们是55,62和43。
请再试一次。

糟糕的是,代码在两个不同的分支中具有相同的逻辑。更好:

if (startIndex > endIndex) return 0;
else 
    return
       (numbers[startIndex] > 0 ? 1 : 0) 
       + countPositives(numbers, startIndex+1, endIndex);
此外,要计算整个阵列,请执行以下操作:

countPositives(numbers, 0, length.numbers-1);

你的缩进到处都是,你应该纠正它,这样你的代码更容易阅读。Eclipse可以为您做到这一点。它对我来说很好。如果我使用
countPositive(新的int[]{2,3,4,5,6},0,4)
结果是
5
。您使用的索引的开始和结束是什么?他可能使用indexStart作为1,它应该是0不,我从0开始