-2

我试图让 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");
    }
}
4

3 回答 3

4

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

您将返回类型设置为String

public static String leapYear(int y)

你返回一个 String 而不是一个 int

return "IT IS NOT A LEAP YEAR";
于 2012-10-12T11:07:15.597 回答
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 ;
}
于 2012-10-12T11:14:36.667 回答
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");
    }
}
于 2014-03-28T21:40:42.320 回答