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);
}
}
-
1When 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.Tdorno– Tdorno2015-01-23 00:39:23 +00:00Commented Jan 23, 2015 at 0:39
3 Answers
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.
Comments
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
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";
}