Java Assignment,Flawed Logic

时间:2012-09-27 17:34:08

标签: java

首先,我知道当你问这些问题时你们不喜欢它,但是我无法看到我的代码有什么问题,并希望有人来看看。话虽如此,我知道我的代码看起来很糟糕,因为这必须在一种方法中完成。

public static int dayOfWeek(int year, int month, int day) {
    int monthCode = 0, centuryCode = 0, numLeapYears = 0, dayOfWeek = 0;

    int yearDigits = year % 100;

    if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
        numLeapYears = yearDigits / 2 + 1;
    }else {
        numLeapYears = yearDigits / 2;
    }

    if(((year >= 1400) && (year <= 1499)) || ((year >= 1800) && (year <= 1899)) || ((year >= 2200) && (year <= 2299))) {
        centuryCode = 2;
    }else if(((year >= 1500) && (year <= 1599)) || ((year >= 1900) && (year <= 1999)) || ((year >= 2300) && (year <= 2399))) {
        centuryCode = 0;
    }else if(((year >= 1600) && (year <= 1699)) || ((year >= 2000) && (year <= 2099)) || ((year >= 2400) && (year <= 2499))) {
        centuryCode = 5;
    }else if(((year >= 1700) && (year <= 1799)) || ((year >= 2100) && (year <= 2199)) || ((year >= 2500) && (year <= 2599))) {
        centuryCode = 4;
    }

    switch(month) {
        case 1: monthCode = 0;
        break;

        case 2: monthCode = 3;
        break;

        case 3: monthCode = 3;
        break;

        case 4: monthCode = 6;
        break;

        case 5: monthCode = 1;
        break;

        case 6: monthCode = 4;
        break;

        case 7: monthCode = 6;
        break;

        case 8: monthCode = 2;
        break;

        case 9: monthCode = 5;
        break;

        case 10: monthCode = 0;
        break;

        case 11: monthCode = 3;
        break;

        case 12: monthCode = 5;
        break;
    }

    dayOfWeek = ((centuryCode + yearDigits + numLeapYears + monthCode + day) % 7);
    return dayOfWeek;
}//dayOfWeek

我还没有费心去评论我的代码,这个函数的目的是计算一个日期(星期日,星期一等)由数字(0,1,2等)表示的日期。)我的代码有效,但它没有输出正确的数字。例如,7/20/1969应该是0,但我的代码输出3.我似乎无法找到我的逻辑中这个方法的缺陷。

1 个答案:

答案 0 :(得分:0)

您月中的开关会关闭 - 日历索引从0开始的月份。因此,1月份的日期为cal.get(Calendar.MONTH) == 0

话虽如此,但您没有提供monthCode代表什么的解释,这使得提供任何类型的帮助变得非常困难。