Error “this method must return a result of type int”?

后端 未结 6 2056
攒了一身酷
攒了一身酷 2021-01-28 03:06

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

6条回答
  •  [愿得一人]
    2021-01-28 03:23

    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:

    • There is no need to cast an int into an int.
    • An unrelated issue is that your code uses a lot of "magic" numbers and you will want to avoid using them.

提交回复
热议问题