dzag30
dzag30

Reputation: 1

Missing Return Statement Error java

public String getValue(int n) 
{
    if (n % ham == 0 || n % spam==0)
    {
        if(n % ham == 0 && n % spam == 0)
        {
            return "hamspam";
        }
        else if(n % ham == 0 && n % spam != 0)
        {
            return "ham";
        }
        else if(n % ham != 0 && n % spam==0)
        {
            return "spam";
        }
    }
    else
    {
        return Integer.toString(n);
    }
}

Upvotes: 0

Views: 344

Answers (3)

jnd
jnd

Reputation: 754

In your first if statement, you need an else clause or a return value.

To elaborate, what if:

if (n % ham == 0 || n % spam==0) //is true

 if(n % ham == 0 && n % spam == 0) // is false
    {
        return "hamspam";
    }
    else if(n % ham == 0 && n % spam != 0) //is false
    {
        return "ham";
    }
    else if(n % ham != 0 && n % spam==0)//is false
    {
        return "spam";
    }

Upvotes: 0

Joe Inner
Joe Inner

Reputation: 1470

public String getValue(int n) 
{
    if (n % ham == 0 || n % spam==0)
    {
        if(n % ham == 0 && n % spam == 0)
        {
            return "hamspam";
        }
        else if(n % ham == 0 && n % spam != 0)
        {
            return "ham";
        }
        else if(n % ham != 0 && n % spam==0)
        {
            return "spam";
        }

        // this return is missing
        return "something";
    }
    else
    {
        return Integer.toString(n);
    }
}

Upvotes: 1

rgettman
rgettman

Reputation: 178343

Logically, we may conclude that if n is a multiple of ham or of spam, then either n is a multiple of both, or of exactly one of the two. We can logically conclude that there is no way that inside the outer if, at least one of the 3 conditions inside will be true and a return will be executed.

But the Java compiler is not that smart. It just sees no return past the last else if in the block, and concludes that there is an execution path that doesn't have a return, so it gives the compilation error.

Logically, if the first 2 conditions are false, given the outer if, the third condition must be true.

Replace

else if(n % ham != 0 && n % spam==0)

with

else

It is logically equivalent, and the compiler will also be satisfied that every execution path has a return statement.

Upvotes: 1

Related Questions