闰年方法

时间:2012-10-12 11:00:23

标签: java

我试图让方法LeapYear返回它是否是LeapYear(返回它实际上是if语句)。本质上,我是编码的新手,我不知道如何返回字符串值而不是int或double。有人可以帮我吗?

public static int LeapYear(int y) {

    int theYear;
    theYear = y;

    if (theYear < 100) {
        if (theYear > 40) {
            theYear = theYear + 1900;
        } else {
            theYear = theYear + 2000;
        }
    }

    if (theYear % 4 == 0) {
        if (theYear % 100 != 0) {
            System.out.println("IT IS A LEAP YEAR");
        } else if (theYear % 400 == 0) {
            System.out.println("IT IS A LEAP YEAR");
        } else {
            System.out.println("IT IS NOT A LEAP YEAR");
        }
    } else {
        System.out.println("IT IS NOT A LEAP YEAR");
    }
}

3 个答案:

答案 0 :(得分:4)

  

我不知道如何返回字符串值而不是int或double。

您将返回类型设为String

public static String leapYear(int y)

并返回String而不是int

return "IT IS NOT A LEAP YEAR";

答案 1 :(得分:1)

public static String LeapYear(int y) {
 int theYear;
 theYear = y;
 String LEAP_YEAR = "IT IS A LEAP YEAR";
 String NOT_A_LEAP_YEAR = "IT IS NOT A LEAP YEAR";

 if (theYear < 100) {
    if (theYear > 40) {
        theYear = theYear + 1900;
    } else {
        theYear = theYear + 2000;
    }
 }

if (theYear % 4 == 0) {
    if (theYear % 100 != 0) {
        //System.out.println("IT IS A LEAP YEAR");
        return LEAP_YEAR;

    } else if (theYear % 400 == 0) {
        //System.out.println("IT IS A LEAP YEAR");
        return LEAP_YEAR;
    } else {
       // System.out.println("IT IS NOT A LEAP YEAR");
       return NOT_A_LEAP_YEAR ;
    }
  } else {
    //System.out.println("IT IS NOT A LEAP YEAR");
    return NOT_A_LEAP_YEAR ;
  }
 return NOT_A_LEAP_YEAR ;
}

答案 2 :(得分:1)

您可以使用以下方法:

static boolean isLeapYear(final int year) {
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

所以:

public static void LeapYear(int y) {
    if (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) {
        System.out.println("IT IS A LEAP YEAR");
    } else {
        System.out.println("IT IS NOT A LEAP YEAR");
    }
}
相关问题