0

I have problem in calculate the average of all the non-negative numbers in the array, zero inclusive, and return zero otherwise. Below is my coding, please help me to check which parts is incorrect. Thanks.

  public class AverageOfNonNegativeNumbers {

  public static double averageOfNumbers(double[] x) throws Exception {
    double avg = 0.1;
    if (x != null) {
        for (double i = 0.1; i < x.length; i++) {
            if ( x[i]%2 == 0 ) {  //Anyone know how to set avoid calculate for negative numbers?
                avg = avg / x[i];  //This code is calculate total average number. 
            }
        }
    }
    return avg;
}

public static void main(String args[]) {
    double x[] = {1.663, -2.1312, 3.13231, 4.124, -5.551, -6.1312, 7.111, 8.222, -9.01};
    try {
        System.out.println(AverageOfNonNegativeNumbers.averageOfNumbers(x));
    } catch (Exception e) {
        System.out.println("Error!!!");
    }
}
}

5 Answers5

1

Define 2 variables to store the sum of non-negative numbers and the count of non-negative numbers.

Then iterate through the array and check each element for non-negativity. If non-negative, add that value to the sum and increment the count by 1.

Finally, divide the sum by count to get the average.

public static double averageOfNumbers(double[] x) {
    double sum = 0; // Variable to store the sum
    int count = 0; // Variable to keep the count

    if (x != null) {
        for (int i = 0; i < x.length; i++) {
            double value = x[i];
            if (value >= 0) { // Check if the number is non-negative
                sum += value; // Add the value to the current sum
                count++; // Increment the count by 1
            }
        }

    }
    return (count > 0) ? (sum /count) : 0; // Calculate the average if there were any non-negative numbers

}
Udith Gunaratna
  • 2,091
  • 1
  • 13
  • 17
1

Following are the issues:

a.you are trying to access the x[i], but i needs to be integer type, while you have it as double

b. x[i]%2 == 0 checks if number is even or not. need to change that to x[i] >= 0

c. Logic to calculate average is not correct.

public class AverageOfNonNegativeNumbers {

  public static double averageOfNumbers(double[] x) {
    int elements = 0;
    double sum = 0;
    if (x != null) {
        for (int i = 1; i < x.length; i++) {
            if ( x[i] >= 0 ) {  // changed this check if number is negative or not
                sum += x[i];  //This code calculates total sum of all non-negative numbers
                elements++;     // and also how many of such no exists
            }
        }
    }
    return sum/elements;
}

public static void main(String args[]) {
    double x[] = {1.663, -2.1312, 3.13231, 4.124, -5.551, -6.1312, 7.111, 8.222, -9.01};
    try {
        System.out.println(AverageOfNonNegativeNumbers.averageOfNumbers(x));
    } catch (Exception e) {
        System.out.println("Error!!!");
    }
}
}
Ankur
  • 892
  • 6
  • 11
0

You're trying to use a double as an index to an array; this doesn't really make sense. An array must be indexed by an integer. That is, an array consists of an element in position 0, position 1, 2, etc.; it doesn't really make much sense to say 'the array element at position 0.1'.

To make your code compile, you will need to declare variable 'i' in your for loop in function 'averageOfNumbers' as an 'int' and not a 'double'.

0

Modifications in you code: According to your question you want to calculate the average of all negative numbers including 0.

Errors:

  1. The method to check if a number is less than 0. %2 checks if the number is even or not.
  2. The way to calculate average is calculate the sum and count and then divide them to minimize the floating point errors.

    public static double averageOfNumbers(double[] x){
    
    double avg = 0.0;
    double sum = 0.0;
    int count=0; 
    if (x != null){
        for (int i = 0; i < x.length; i++){
            if ( x[i]>=0 ){  
                sum = sum + x[i];  
                count=count+1; 
            }
        }
    }
    if(count!=0){
      avg=sum/count;
    }
    return avg;
    }
    
Apurva Singh
  • 411
  • 3
  • 14
0

A simle one-Liner using Java 8 Strems:

double avg=Stream.of(x).mapToDouble(d->d).map(num->num<=0).average().orElse(0.0);

It creates a DoubleStream (mapToDouble) and removes all numbers greater than 0 and calculates the average.

If there is no result(because x is empty) it will return 0.

See this for reference.

dan1st
  • 12,568
  • 8
  • 34
  • 67