Given an array of integers, I need to return a new array containing the middle element(s) from the original array. Specifically, the result will have one element if the length o
Try this code:
public int[] makeMiddle(int[] nums) {
int[] a;
if (nums.length %2 == 0) {
// even-length array (two middle elements)
a = new int[2];
a[0] = nums[(nums.length/2) - 1];
a[1] = nums[nums.length/2];
} else {
// odd-length array (only one middle element)
a = new int[1];
a[0] = nums[nums.length/2];
}
return a;
}
In your original code, you were not checking whether the length of nums
be even or odd.