Problem of the Day
Tuesday, February 24, 2026
Problem:
The static method evenSurrounded is intended to take an Array of integers as a parameter and examine it, returning true if there is at least one occurrence of an even value that is surrounded on both sides by odd values. The Array {3, 8, 1, 7} should return true because the even value 2 is surrounded by two odd values, while the Array {8, 1, 3, 7} should return false because the even value 2 is not surrounded on both sides by odd values.
The code given here attempts to implement this method.
/**
* Returns true if there is at least one even number in a list
* surrounded on both sides by non-even (odd) numbers.
*/
public static boolean evenSurrounded(int[] nums)
{
for (int i = 1; i < nums.length; i++)
{
if (nums[i] % 2 == 0)
{
if (nums[i - 1] % 2 == 1 && nums[i + 1] % 2 == 1)
return true;
}
}
return false;
}
For which circumstances will the method not work?
- When there is an even number in the first position
- When there is an even number in the second position
- When there is an even number in the next-to-last position
- When there have been no even numbers up until the last position
The correct answer is d. If we haven't yet found an even value surrounded and returned true, evaluating the final number in the list will, according to this algorithm, attempt to access the value at index nums.length, an index which doesn't exist, and thus producing an ArrayIndexOutOfBoundsException error.
To fix this issue, the for-loop should be written as
for (int i = 1; i < numslength - 1; i++)