Search code examples
javasearchreturnsequential

Sequential Search Java Missing Return Statement?


I don't understand why I keep getting the error of "missing return statement." Any help is appreciated. Thank you.

//sequential search
public static int seqSearch(int[] items, int goal)throws IOException
{
    int c;
    for (c = 0; c < items.length; c++)
    {
        if (items[c] == goal)     // Searching element is present
            return c;
    }
    if (c == items.length)  // Searching element is absent
        return (-1);
}//end seq

Solution

  • You return something only if items[c] == goal inside the loop or if (c == items.length). This means that you return -1 at the last iteration but if you've got that far you've already iterated through the whole array. Replacing

    if (c == items.length)  // Searching element is absent
            return (-1);
    

    with just

    return (-1);
    

    should do the job