2

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;
}
J. Bel
  • 21
  • 1
  • 1
    The compiler is right. If `nums` is empty (length zero), then `newi` will not have been initialized. You need to provide an initial value (like `null` or `{}`). – Thilo Jan 22 '16 at 04:15
  • 1
    Also, you are creating a new array in every loop iteration. That does not seem right. – Thilo Jan 22 '16 at 04:17
  • [why you need to initialize local variables](http://stackoverflow.com/q/415687/4506140) – Jude Niroshan Jan 22 '16 at 04:20

2 Answers2

0

You would need to first find the length of the in array, and then init the array. You can't have int[] newi; just laying there since it is not initialized. I suggest using a counter and if the counter exceeds 2, init the array at 2.

voice
  • 1,326
  • 1
  • 11
  • 16
0

In these kind of situation, I always use to do like

public int[] frontPiece(int[] nums) {
   int[] newi = null;
     //Your codes
   return newi;
}

I use to retrieve array like this

int[] returnedIntArray = frontPiece(//Some parameter);

And after that I use to check if null or not

if(returnedArray != null){
     // Do stuff if returnedArray has values, this means your method  returned array with value
 }
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68