0

I keep getting a return statement error for this section of code. Looks fine to me, maybe someone in here can help?

//It returns the index of the number specified by the parameter is
//located. If the number is not found, it returns -1.
private int indexOf(int searchingNum) {
    for (int index = 0; index < count; index++)
        if (numberArray[index] == searchingNum) {
            return index;
        } else 
            return -1;
}
1
  • 2
    Your indentation suggests that your code does not do what you think it does. Commented Nov 15, 2013 at 16:30

5 Answers 5

2

for the compiler, this method does not contain a return statement that is guaranteed to be executed in any case. you have a return in your for loop, but the compiler does not know if at least one iteration will be executed, and therefore it is not sure if the return statement will be executed

Sign up to request clarification or add additional context in comments.

Comments

2

your last else is not needed

//It returns the index of the number specified by the parameter is
//located. If the number is not found, it returns -1.
private int indexOf(int searchingNum)
{
    for (int index = 0; index < count; index++)
        if (numberArray[index] == searchingNum){
            return index;
        }
    }
    return -1;
}

Comments

0

Currently of what you have will return -1 always with exception when numberArray[0] has searchingNum. what you probably meant is this:

private int indexOf(int searchingNum)
{
    for (int index = 0; index < count; index++) {
        if (numberArray[index] == searchingNum) {
            return index;
        }
    }
    return -1;
}

also sub the count to numberArray.length - this will save some time for you in case count is not equals to length of numberArray

Comments

0

The problem is what happens when the for loop is not executed, what will be returned? You have a path that does not return an expected value as specified by the return type of the method.

Comments

0

Its giving missing return statment error beacuse all of your return statement is in if-else statement. There must be atleast on return statument outside the scope of all your conditional statements including the loops.

private int indexOf(int searchingNum) {
for (int index = 0; index < count; index++)
if (numberArray[index] == searchingNum){
  return index;
}
else return -1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.