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 of the original array is odd, and two elements if it's even.
This is my code right now, which works for arrays of even length. How do I make it work for arrays with odd length?
public int[] makeMiddle(int[] nums) {
int[] a = new int[2];
if(nums.length>1) {
a[1]=nums[nums.length/2];
a[0]=nums[nums.length/2-1];
return a;
} else {
a[2]=nums[((nums.length+1)/2) -1];
}
return a;
}