I am trying to create a method that searches through an array for a user specified name and return its position in the array, or -1 if the name isnt found. I thought I had it but I get an error stating “not all code paths return a value” The code is throwing it in the name of the method, so its not being very specific, though with the error I wasnt expecting to much specificity.
anyway, here is the code, can anyone tell me what is throwing the error?
static int FindStudent()//search for student name
{
while (z < NameArray.Length)
{
if (name == NameArray[z])
{
return z;
}//end if statement
else
{
z++;
}//end else statement
}//end while loop
if (z==5)
{
return -1;
}//end student not found
}//end FindStudent method
Remove your final if statement. As your code is now, it will only return -1 if there are exactly 4 items in your array and none of them match. For that matter, you could also remove your else as well; Because the if above it returns, the else is implied.