3

这是我更新的代码,它仍然不起作用。对于 2 月 29 日的所有情况,它返回天,当它应该只在闰年返回天时,如果不是闰年,应该返回 1。

public int checkDay (int day)
{
    // For months with 30 days.
    if ((month == 4 || month == 6 || month == 9 || month == 11) && day <= 30)
        return day;
    // For months with 31 days.
    if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day <= 31))
        return day;
    // For leap years.
    // If February 29th...
    if (month == 2 && day == 29)
    {
        // Check if year is a leap year.
        if ((year%4 == 0 && year%100!=0) || year%400 == 0) 
        {
            // If year is a leap year return day as 29th.
            return day; 
        }
        // If not a leap year, return day as 1st.
        else return 1;
    }
    // If Date if February 1st through 28th return day, as it is valid.
    if (month == 2 && (day >= 1 && day <= 28))
        return day;
// Return day as 1st for all other cases.
return 1;
}
4

3 回答 3

5

试试 GregorianCalendar http://docs.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html

GregorianCalendar gc = new GregorianCalendar();
if (gc.isLeapYear(year) ) 
于 2013-09-04T07:21:23.007 回答
1

尝试将您的代码更改为

if (year%4==0&&(year%100!=0&&year%400==0)) 
于 2013-09-04T07:22:22.973 回答
0
if ((year%4==0 && year%100!=0) || year%400==0)

这解决了你的问题,你的逻辑是错误的:)

试试这个代码:如果返回的布尔值是假的,你可以将日期设置为 1,因为日期无效。

public bool checkDay (int day, int month, int year){
    bool valid = false;
    if(day >=1){
        // For months with 30 days.
        if ((month == 4 || month == 6 || month == 9 || month == 11) && day <= 30){
            valid = true;
        }
        // For months with 31 days.
        if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day <= 31){
            valid = true;
        }
        // For February.
        if (month == 2)
        {
            if(day <= 28){
                valid = true;
            } else if(day == 29){
                if ((year%4 == 0 && year%100!=0) || year%400 == 0){
                    valid = true;
                } //else invalid
            }
        }
    } //else date is not valid
    return valid;
}

更好的做法是在每个方法中只有一个 return 语句。这使得更容易理解代码并通过它来调试它并发现可能的错误。如果您有任何问题,请随时询问。

于 2013-09-04T07:25:47.020 回答