2014-09-22 33 views
2
public static void main(String [] args) 
{ 
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter the month (1-12):"); 
    int month = input.nextInt(); 
    System.out.print("Enter the day (1-31):"); 
    int day = input.nextInt(); 
    System.out.print("Enter the year (ex. 2014):"); 
    int year = input.nextInt(); 

    if (month == 1) 
     month = 13; 
    else if (month == 2) 
     month = 14; 

    int Zeller = day + ((26 * (month + 1))/10) + year + 
     (year/4) + (6 * (year/100)) + (year/400); 

    int dayofweek = (Zeller + 5) % 7 + 1; 

    if (dayofweek == 1) 
     System.out.print("Day of the week: Monday"); 
    else if (dayofweek == 2) 
     System.out.print("Day of the week: Tuesday"); 
    else if (dayofweek == 3) 
     System.out.print("Day of the week: Wednesday"); 
    else if (dayofweek == 4) 
     System.out.print("Day of the week: Thursday"); 
    else if (dayofweek == 5) 
     System.out.print("Day of the week: Friday"); 
    else if (dayofweek == 6) 
     System.out.print("Day of the week: Saturday"); 
    else if (dayofweek == 7) 
     System.out.print("Day of the week: Sunday"); 
} 

該代碼將不會正確計算1月和2月的日期。它總是一兩天。澤勒的同餘代碼錯誤

例如:如果我輸入Jan 1, 2010,代碼應該輸出Day of the week: Friday,但相反,它說它的Day of the week: Saturday

我檢查了我的計算結果找不到任何錯誤。

+2

我害怕的'年/ 100','年/ 400',和其他整數部門。 – 2014-09-22 18:19:00

+0

我應該在這裏做什麼?宣佈一個新的整數? – Michael 2014-09-22 18:23:33

+1

當你說你已經「檢查了你的計算」,你在做整數除法嗎?如果這個術語對你來說沒有任何意義,那很可能是你的bug的根源。 – dimo414 2014-09-22 18:27:14

回答

5

根據Zeller's congruence wiki page,當您調整1月和2月份時,還必須調整年份,因爲該算法依賴於1月和2月被視爲前一年的「第13次」和「第14次」月份。

但在使用計算機時,它是簡單的處理改性Y年,其爲Y - 1月1日和二月期間:

年調整的代碼添加到您的一月和二月的情況。

if (month == 1) 
{ 
    month = 13; 
    year--; // add this 
} 
else if (month == 2) 
{ 
    month = 14; 
    year--; // add this 
} 

輸出爲1月1日的測試案例,2010:

Enter the month (1-12):1 
Enter the day (1-31):1 
Enter the year (ex. 2014):2010 
Day of the week: Friday 

的情況下,以上可以簡化:

if (month == 1 || month == 2) 
{ 
    month += 12; 
    year--; 
} 
+0

2008年2月29日 2015年1月17日1776年7月4日這些日期還沒有生成 – Michael 2014-09-22 18:30:12

+0

2008年2月29日是星期五。 2015年1月17日將是星期六。 1776年7月4日是星期四。我的程序副本隨着我的更改得到了正確的結果。 – rgettman 2014-09-22 18:34:38

+0

我做了這些改變,但仍然不會給我正確的日期。 – Michael 2014-09-22 18:37:51