0
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);
    }
}
1
  • 1
    When inside a method you must specify a return path for all possible paths. In this case there exists a path where your three if/elseif conditions may all evaluate to false and no return path is defined. Commented Jan 23, 2015 at 0:39

3 Answers 3

1

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.

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

Comments

1
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);
    }
}

Comments

0

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";
    }

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.