M.Mir M.Mir - 1 month ago 6
Java Question

I want to print odd numbers in an array using methods

This code print the array (1, 7, 8, 22, 37, 55, 80) the way it is without calculating its evens.

The output that I want (8, 22, 80).

The output that I get (1, 7, 8, 22, 37, 55, 80).

///The getEvens() method
public static int[] getEvens(int a[]) {

int myEvens = 0;

for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
myEvens++;
}
}

Arrays.sort(a);

return a;
}

\\\\The main method
public static void main(String args[]) {

int [] getEvens;
int [] myArray = {1,8,80,22,55,37,7};
int [] evenResult = getEvens(myArray);

System.out.print("\nThe even numbers in the array(" + Arrays.toString(myArray)+ ") are:{ " + Arrays.toString(evenResult)+ "}.");

}

Answer

In the getEvens method you do not make a new array out of the even numbers. All you do is count them. You need to change it to something like the following:

public static int[] getEvens(int a[]) {
    int myEvens = 0;

    for (int i = 0; i < a.length; i++) {
      if (a[i] % 2 == 0) {
         myEvens++;
      }    
    }

    //the code to actually add the evens to a new array
    int[] evenArray = new int[myEvens];
    int evenIndex = 0;
    for (int i = 0; i < a.length; i++) {
      if (a[i] % 2 == 0) {
        evenArray[evenIndex] = a[i];
        evenIndex++;
      }    
    }
    Arrays.sort(evenArray);

    return evenArray;
}
Comments