문제

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
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top