My objective is to write a method that creates a copy of an array with the odd numbers removed. Here is my code:
public class Evens {
static int[] evens(int[] input) {
final int n = input.length;
int[] output = new int[n];
for(int i=0;i<n;i++) {
if(input[i]%2 == 0)
output[i] = input[i];
}
return output;
}
public static void main(String[] args) {
int[] fvalues = new int[] {4,7,9,3,6,8,2};
int[] evalues = evens(fvalues);
for(int i=0;i<evalues.length;i++)
System.out.println(i+"] "+evalues[i]);
}
}
When I run it, It gives me the elements of an array with all the even numbers of the original array but with zeros where the odd numbers were. How can I write it so there are no zeros with the odd numbers just gone?
For removing an element you're better off using an ArrayList, since an array can't change its size. If you have to use arrays, then the output array must be shorter than the input. Say, if you're going to remove three elements, then the size of output will have to be input.length-3.
In your implementation, you're not actually removing elements, you just skip over the odd numbers, and since an int[] is initialized by default to zeros, the places where the odd numbers used to be appear with zeros on them.
You can do this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With