. Advertisement .
..3..
. Advertisement .
..4..
I am tired of fixing the problem: not all code paths return a value in C# in the csharp; even if I get the reference from another forum, it still returns an error:
error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value
To identity the problem, I will show you the detail here:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
}
How do I do that? Could you support me in improving this problem?
You are missing a
The compiler will look at your code and see a third path (the
My suggestion was to add a return
assertion.
else
that you didn’t code) that could exist but does not return any value. not all code paths return a value
is the result.
return
value to the if-else-if
after your loop ends. Another obvious spot is adding a else
with a return
value in the if-else-if
. This would break the for
loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
The cause: You are missing a return assertion. The compiler will look at your code and see a third path (the else that you didn’t code) that could exist but does not return any value. not all code paths return a value is the result.
Solution: My suggestion was to add a return value to the if-else-if after your loop ends. Another obvious spot is adding a else with a return value in the if-else-if. This would break the for loop.
The compiler does not understand the complex logic of returning in the last loop iteration. It thinks you could exit the loop without ever returning anything.
Do not return in the previous iteration. Instead, return true after the loop.
Side note: There is a logic error in the original code. While you are checking
num == 20
in this last condition, it is important to checkj == 20
. You should also check ifnum % j == 0
is superflous. This is because it is always true once you reach there.