简体   繁体   中英

How to calculate the average of even and odd numbers in an array?

As a class exercise I have to code using methods a program that:

1) Calculates the average of even and odd numbers in an array.

I expect on using one method to find the average of even and odd numbers. However, I'm having trouble on returning the right average. For example, if I enter only odd numbers I get an error, and vice versa.

This error: "java.lang.ArithmeticException: / zero"

Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for:

2) Print the highest and lowest number in the array 3) Allow the user to modify any of the numbers of the array

So far I have this code:

public static void main (String args[]){

    int x[] = new int[4];
    Scanner input = new Scanner(System.in);

    for(int i = 0; i < x.length ; i++){
        System.out.println("Enter a number: ");
        x[i] = input.nextInt();
    }


    System.out.println("Average of even numbers: " + getAverage(x));
    System.out.println("Average of odd numbers: " + getAverage(x));

 }

public static int getAverage(int a[]){
    int add_even = 0;
    int counter_even = 0;
    int average_even = 0;

    int add_odd = 0;
    int counter_odd = 0;
    int average_odd = 0;


    for(int i = 0; i < a.length; i++){
        if(a[i] % 2 == 0){
            add_even += a[i];
            counter_even++;
        }
        else if(a[i] % 2 == 1) {
            add_odd += a[i];
            counter_odd++;
        }

    }

    if (add_even % 2 == 1 && add_odd % 2 == 1){
    average_even = 0;
    average_odd = add_odd / counter_odd;

    return average_even;
   }
   else if (add_even % 2 == 0 && add_odd % 2 == 0){
    average_even = add_even / counter_even;
    average_odd = 0;

    return average_even;
    }
   else{

    average_even = 0;
    average_odd = add_odd / counter_odd;

    return average_odd;

    }


} 

Thank you!

You have a divide by zero error cropping up here.

else if (add_even % 2 == 0 && add_odd % 2 == 0){
    average_even = add_even / counter_even;
    average_odd = 0;
    return average_even;
}

0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. You'll need to account for that in your code by checking if counter_even is 0.

else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){

1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int . It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. To handle the ArithmeticException just return 0 if there are no values.

public static int average(int[] n, boolean even) {
     int total = 0;
     int count = 0;
     for (int i = 0; i < n.length; i++) {
          if (even == (n % 2 == 0)) {
               total += n;
               count ++;
          }
     }
     if (count == 0)
          return 0;
     return total / count;

2)To check find the max and min value simply loop through the array like this

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

for (int i = 0; i < x.length; i++) {
     if (x[i] < min)
          min = x[i];
     if (x[i] > max)
          max = x[i];
}

3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this.

System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
     System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();

You can then run a method that changes the value of the array

edit(x, index, value);

public static int edit(int[] n, int index, int value) {
     n[index] = value;
     return n;
}

Your get average looks more complicated then it needs to be.

First off the getAverage(x) :

System.out.println("Average of even numbers: " + getAverage(x));
    System.out.println("Average of odd numbers: " + getAverage(x));

will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even.

In your method you should loop through all the numbers and check if it is even. If it is even and you are averaging evens add it to a "total" and add one to a counter. At the end divide "total" by the counter and return the value. The average will most likely include a decimal value, so you should return a double or a float.

Example:

public static double getAverage(int a[], boolean even){
  double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
    double counter = 0;
  for(int i = 0; i<a.length; i++){
    if(a[i] % 2 == 0 && even){//even
      counter++;
      total += a[i];
    }else{//odd
      counter++;
      total += a[i];
    }
  }
  if(total == 0){//Avoid dividing by 0.
    return 0; //You can also throw an exception instead of returning 0.
  }
  return total / counter; //Returns the average for even or odd numbers.
}

For the second part of your question you need to loop through the numbers and find the highest and lowest while looping.

Example:

int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
  if(x[i] > highest){
    highest = x[i];
  }
  if(x[i] < lowest){
    lowest = x[i];
  }
  if(i == 0){
    highest = x[i];
    lowest = x[i];  
  }
}

I used JS for this task, you can just rewrite my code to Java language.

A number is divisible by 2 if the result of its division by 2 has no remainder or fractional component - in other terms if the result is an integer. Zero is an even number because when 0 is divided by 2, the resulting quotient turns out to also be 0 - an integer (as a whole number that can be written without a remainder, 0 classifies as an integer).

 function compareEvenOddAverage(arr) { let even = 0, odd = 0, evenCounter = 0, oddCounter = 0, str = ''; for (let i = 0; i < arr.length; i++) { if (arr[i] % 2 === 0) { even += arr[i]; evenCounter++; } else { odd += arr[i]; oddCounter++; } } if (even / evenCounter > odd / oddCounter) { str += 'Average value of even numbers is greater'; } else if (even / evenCounter < odd / oddCounter) { str += 'Average value of odd numbers is greater'; } else { str += 'Average values are equal'; } return str; } console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5])); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM