错误“此方法必须返回类型为int的结果”? [英] Error "this method must return a result of type int"?

查看:189
本文介绍了错误“此方法必须返回类型为int的结果”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有这段代码,它一直告诉我感恩节()必须返回int的结果类型。我已将所有结果转换为确定值,但似乎没有任何效果!为什么会出现此错误?

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 working! Why am I getting this error?

public class Thanksgiving
{
private static final int YEAR = 2000;  // first valid year for this method
private static final int NOV1 = 3;     // 2000/11/01 falls on a Wednesday
private static final int THURS = 4; // (Sun = 0, Mon = 1, ..., Sat = 6)

// Precondition: year > 1999
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 );
  }
}
public static int firstOfMonth(int year)
{
  int raw = year - 2000;
  int day = NOV1;
  for(int i = 0; i < raw; i++ )
  {
    if( i % 4 == 0 )
    {
      day = day + 2;
    }
    else
    {
      day++;
    }
  }
  return day % 7;
}

public static void main(String[] args)
{

    for(int year = 2000; year <= 2100; year++)
    {
        System.out.print("T'giving " + year + " is Nov " + thanksgiving(year) + "; ");
        if (year % 3 == 1)
        {
            System.out.println();
        }
    }
}

}

推荐答案

在此代码中:

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

您要在多个if块中制作返回语句。如果它们都不是真实的怎么办?编译器将不允许这样做,您应该在底部返回默认值或引发异常。否则,如果不是,则另作一些if语句:

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

也:


  • 不需要将int转换为int。

  • 一个不相关的问题是,您的代码使用了很多魔术数字,您将希望避免使用它们。 li>
  • 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.

这篇关于错误“此方法必须返回类型为int的结果”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆