I have this recursive method that counts the amount of negative numbers that lie in the array called "NumArray"

public static int countNegative(double[] NumArray, int startIndex, int endIndex)
{
	if (startIndex == endIndex)
	{
		if (NumArray[startIndex] < 0)
		{
			return 1;
		}

		else

			return 0;
    }

	else if (NumArray[endIndex] < 0)
		{
			return 1 + countNegative(NumArray, startIndex, endIndex - 1);
		}

		else

			return countNegative(NumArray, startIndex, endIndex - 1);

In my main code I use this print state to print it:

int negCount = countNegative(NumArray, 0, NumArray.length -1); //setting negCount equal to the method

System.out.println ("The total count of negative numbers is " + negCount + ('\n'));

When I start the program and I put in a negative numbers it won't print after when a 0 is entered //When 0 is entered it'll stop taking in inputs from the user and display the amount I have.

Am I doing something wrong? Is my recursive method not reading in negative values?

Hi BboyRodimus,

How are you populating NumArray? I tried your code by declaring and initializing NumArray in main() and it works.

public static void main(String[] args) {
		double[] numArray = {0,-1, -2, 5, 6, 0, -2.5, -3.5, 0, -74};
		
		int negCount = countNegative(numArray, 0, numArray.length -1);
		System.out.println("The total count of negative numbers is " +
				negCount + "\n");

	}

I'm guessing could be a different part of your program that's causing the problem.

I'm new to Java myself and I wouldn't be surprised of some of the Java pros jump in and spot the problem right away :)

The code you have posted here seems fine. Can you post the code that prompts the user for input?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.