1,105,380 Community Members

Java program wont read in negative numbers

Member Avatar
BboyRodimus
Newbie Poster
16 posts since Aug 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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?

Member Avatar
Overbooked
Light Poster
34 posts since Nov 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

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 :)

Member Avatar
apines
Practically a Master Poster
618 posts since Apr 2007
Reputation Points: 116 [?]
Q&As Helped to Solve: 56 [?]
Skill Endorsements: 0 [?]
Featured
 
0
 

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

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: