Question

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
Was it helpful?

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

OTHER TIPS

Because both your return statements are inside

if(...){
return
}

So in some scenario your code might "miss" both return statements. That means if none of those if statements are true, your method won't return anything. Do you need to add an else statement to your last if for example, which returns something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top