Could any one tell me how to correct following code to work correctly?
Write a method filterEvens which takes in an array of integers and returns a new array containing only the even values.
new array containing only the even values. Eg:
int[] data = {1, 3, 4, 2, 0, 5, -2};
int[] evens = filterEvens(data);
public static int[] filterEvent(int[] data) {
int countLength = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] % 2 == 0) {
countLength++;
}
}
int[] filArray = new int[countLength];
for (int i = 0; i < data.length; i++) {
if (data[i] % 2 == 0) {
filArray[i] = data[i];
}
}
return filArray;
}
The problem here is:
You’re looping from values 0 –> data.length. That’s an issue because the array filArray[i] is of a smaller length.
Imagine it like this, you’re looking for someone’s house. On the street they give you, let’s say Emerald Dr. The house numbers can be from 2000 – 3000. Then you are told that they live at 4000 Emerald Dr. Same case here, except the computer is trying to find the house.