I have this code below and it keep telling me that thanksgiving() must return a result type of int. I have casted all the results just to make sure, but nothing seems to be work
All the returns are in if statements, in this case, compiler sees that there might be a situation in which the function won't return anything. You need to add one return outside any ifs or in an else statement.
You need something like this
public static int thanksgiving(int year)
{
int day = firstOfMonth( year );
if ( day == THURS )
{
return (int) 22;
} else if ( day > THURS )
{
return (int) 29 - ( day - THURS );
} else {
return (int) 22 + ( THURS + day );
}
}
In this code:
public static int thanksgiving(int year)
{
int day = firstOfMonth( year );
if ( day == THURS )
{
return (int) 22;
}
if ( day > THURS )
{
return (int) 29 - ( day - THURS );
}
if ( day < THURS )
{
return (int) 22 + ( THURS + day );
}
}
You're making your return statement in several if blocks. What if none of them are true? The compiler will not allow this, and you should either return a default value at the bottom or throw an exception. Or else make some of the if statements else - if with a last else:
public static int thanksgiving(int year){
int day = firstOfMonth( year );
if ( day == THURS ) {
return (22;
} else if ( day > THURS ) {
return 29 - ( day - THURS );
} else { // else without the if
// we know that ( day < THURS )
return 22 + ( THURS + day );
}
}
Also:
You have 3 if
statements inside thanksgiving()
method. What if none of the condition gets satisified? What would return in that case? So compiler is complaining.
The problem is that all of your return statements are within an if statement. If, for some reason, day != Thursday, not < thursday, and not > thursday (I know this is impossible), then nothing will be returned. Change your code to have a default return value:
public static int thanksgiving(int year)
{
int day = firstOfMonth( year );
if ( day == THURS )
{
return (int) 22;
}
else if ( day > THURS )
{
return (int) 29 - ( day - THURS );
}
else
{
return (int) 22 + ( THURS + day );
}
}
The Java compiler is too stupid to realize that in every situation, one of your conditions will be satisfied. It sees the if statements and thinks that it is possible that none of them will be satisfied. You can add a return at the end of the method that indicates an error case, you can throw an exception, or you can assert false
.