All puzzles
Per page
Y
Enhanced for · ArrayList · Filter

Keep the even numbers

Return a new ArrayList with the even numbers from the nums array, in the same order.

evens(new int[] {3, 8, 10, 7}) returns [8, 10].

10 strips: Y1 to Y10

return result;
Y1
}
Y2
if (n % 2 == 0) {
Y3
ArrayList<Integer> result = new ArrayList<Integer>();
Y4
}
Y5
public static ArrayList<Integer> evens(int[] nums) {
Y6
result.add(nums[n]);
Y7
}
Y8
for (int n : nums) {
Y9
result.add(n);
Y10

Answer key: Y. Keep the even numbers

Order: Y6, Y4, Y9, Y3, Y10, Y5, Y2, Y1, Y8. Extra: Y7

public static ArrayList<Integer> evens(int[] nums) {
	ArrayList<Integer> result = new ArrayList<Integer>();
	for (int n : nums) {
		if (n % 2 == 0) {
			result.add(n);
		}
	}
	return result;
}

Extra strip: result.add(nums[n]);. In an enhanced for loop, n is the number itself, not an index. When n is 8, nums[8] is past the end of the array.