Joe Heiler
Joe Heiler

Reputation: 5

Using loops to return in a method

So, I need to return either a position in an array or a -1 if the goal number is not found. The problem is when I use return inside an if else statement, I get an error because the program will not go into the if loop. Here is my current code:

public int search(int num1)
{
for(int i=0;i<scores.length;i++)
    {
        if(scores[i]==num1)
        {
            return i;
        }
        else
        {
            return -1;
        }

    }
}

This keeps giving me an error saying no return statement. Is there a way to do this logic without the error? thanks guys

Upvotes: 0

Views: 78

Answers (2)

Joseph118
Joseph118

Reputation: 505

it gives you error because it might think that the loop might not be executed. in order for it to run it has to be a return statement outside a loop or an if statement.

here is an adjustment i did with your code.

    public int search(int num1) {
        int x = -1;
        for(int i = 0; i < scores.length; i++) {
            if(scores[i]==num1) {
                x = i;
            }
        }
        return x;
    }

Upvotes: 0

rgettman
rgettman

Reputation: 178333

If the for loop is not entered, then there is no return statement. This could happen if scores.length is 0. You must supply a return statement in all cases of execution, or the compiler will catch a case without a return statement and give a compiler error.

Move the return -1 after the for loop, so that you only return -1 if you went through the entire loop and didn't find num1. That also means that the else block is unnecessary -- remove it.

Upvotes: 3

Related Questions