Hi,

I keep getting the error message "Missing return statement" after my if else controls.
I have return controls, I'm just not sure if I can implement multiple returns.

For example, I am trying to create a method in which the middle value of a sequence of numbers is returned, regardless of position. (E.g. 2, 1, 3 returns 2, -- 8, 3, 5 returns 5)

Here is my code below

public int mid(int a, int b, int c)
    {
        if ((a != b) && (a != c))
        {
            return a;
        }
        else if ((b != a) && (b != c))
        {
            return b;
        }
        else if ((c != a) && (c != b))
        {    
            return c;
        }
    } (error message here)

Am I getting this error message simply because I have not covered all possible options in the if-else control, or is there another reason?

Your function was missing a final return option.
If c is truly the final option, then change it to this:

public int mid(int a, int b, int c)
{
    if ((a != b) && (a != c))
    {
        return a;
    }
    else if ((b != a) && (b != c))
    {
        return b;
    }
       
    return c;
}

Edited 5 Years Ago by thines01: formatting

Unfortunately I need my final return to be a, b, or c, depending on which it needs to be in the sequence. For example if a = 1, b = 2, and c =3, the return would have to be b. I'm not sure how to use a, b, and c as final return options.

Ah, solved. My problem was more or less in the fact that I should have been using greater than / less than (>, <) operators rather than does not equal operators (!=)

revised code

public int mid(int a, int b, int c)
    {
        if ((a < b) && (a > c))
        {
            return a;
        }
        else if ((a > b) && (a < c))
        {
            return a;
        }
        else if ((b < a) && (b > c))
        {
            return b;
        }
        else if ((b > a) && (b < c))
        {
            return b;
        }
        else if ((c < b) && (c > a))
        {
            return c;
        }
        else
        {
            return c;
        }
    }

thanks for your help, that bit of logic helped me figure it out in the end.

The corrected function will return a or b or c.
The compiler complains because you made it look as if there was to be another option by enclosing the last option in an else statement.

Keep in mind, once the chosen option is reached, the function exits.
There is no danger in leaving the last return unwrapped -- in fact, it's essential.
If there are NO OTHER OPTIONS past a or b, then the final outcome MUST be c, right?

...Please understand that wrapping the return c in an "else" with no options is the SAME THING. It's just syntax. If you understand that, your coding projects will look more professional as they will contain less artificial syntax.

This question has already been answered. Start a new discussion instead.