I need to use this method:
public static int countNegative(double[] numbers, int count){ }
to count the number of negative numbers in a double array. I could easily do it if I could include a 3rd parameter, sum, but I can only use the array and an int. I'm completely stuck. I've tried a few things, but cannot get it right. I've gotten everything from the size of the array to ArrayIndexOutOfBounds, but never the right answer. Could anyone help me out with this?
-EDIT-
Well here is the exact assignment:
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.
Then compute the maximum number stored in the array, the count of negative numbers, and compute the sum of positive numbers, using recursion. Thus you will create recursive methods findMax, countNegative, and computeSumPositive in Assignment9 class and they will be called by a main method.
Specifically, the following recursive methods must be implemented (These method should not contain any loop):
public static double findMax(double[] numbers, int count) -> It finds the maximum number in the array, count is the number of elements
in the array
public static int countNegative(double[] numbers, int count) -> counts the negative integers
public static double computeSumPositive(double[] numbers, int count) -> sums number of positive integers
findMax() was easy:
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));
}
This is my most recent attempt at countNegative. It just returns 99 (I have the array initialized with 100 elements):
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);
}
I should be able to figure out the computeSumPositive if I can figure out this negative one.
Count can be whatever you need it to be. I used it more as an index in findMax.
count
for? It will help a lot if you quote the requirements you've been given in the question, and also show the gist of the code you've tried. – David Z