简体   繁体   中英

Method to add the even/odd numbers

I have an array with several numbers:

int[] tab = {1,2,3,4};

I have to create two methods the first is the sum() method and the second is numberOdd() .

It's Ok for this step !

int length = tab.length;
length = numberOdd(tab,length);

int sum_odd = sum(tab, length);

System.out.println(" 1) - Calculate the sum of the odds numbers :  => " + sum_odd);


public static int sum(int[] tab, int length){
      int total = 0;
      for(int i=0;i<length;i++){
        total += tab[i];
      }
      return total;
}


public static int numberOdd(int[] tab, int length){
      int n = 0;
      for(int i=0;i<length;i++){
        if(tab[i] % 2 != 0){
          tab[n++] = tab[i];
        }
      }
      return n; 
}

Now, I have to add the even numbers with the numberEven() method and I get the value "0".

I don't understand why I retrieve the value => 0 ???????

Here is my code:

int[] tab = {1,2,3,4};

int length = tab.length;
length = numberOdd(tab,length);

int sum_odd = sum(tab, length);

length = numberEven(tab,length);
int sum_even = sum(tab, length);



System.out.println(" 1) - Calculate the sum of the odds numbers :  => " + sum_odd);
System.out.println(" 2) - Calculate the sum of the evens numbers :  => " + sum_even);
}

public static int numberEven(int[] tab, int length){
      int n = 0;
      for(int i=0;i<length;i++){
        if(tab[i] % 2 == 0){
          tab[n++] = tab[i];
        }
      }
      return n; 
}

For information: I share the code here => https://repl.it/repls/CriminalAdolescentKilobyte

Thank you for your help.

you have changed the array in your numberOdd() method. try replacing tab[n++] = tab[i]; with n++;

public static int sumEven(int[] tab){
  int sumEven = 0;
  for(int i=0;i<tab.length;i++){
    if(tab[i] % 2 == 0){
      sumEven = sumEven + tab[i];
    }
  }
  return sumEven; 
}

This should work.

  1. You need to add tab[i] to n
  2. Having length as a parameter to numberEven does not cause any harm but you don't need it.

Given below is the working example:

public class Main {
    public static void main(String[] args) {
        int[] tab = { 1, 2, 3, 4 };
        System.out.println(numberEven(tab));
    }

    public static int numberEven(int[] tab) {
        int n = 0;
        for (int i = 0; i < tab.length; i++) {
            if (tab[i] % 2 == 0) {
                n += tab[i];
            }
        }
        return n;
    }
}

Output:

6

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