My code keeps hitting a compiling error that says that "The local variable newi may not have been initialized," and I can't figure out how to fix it. The task is: Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present.
My code is:
public int[] frontPiece(int[] nums) {
int[] newi;
if (nums.length >= 2)
{
for(int i = 0; i < 2; i++)
{
newi = new int[2];
newi[i] = nums[i];
}
}
else
{
for( int i = 0; i < nums.length; i++)
{
newi = new int[nums.length];
newi[i] = nums[i];
}
}
return newi;
}