2013-03-01 133 views
-3

我需要幫助製作一個程序,該程序需要年份和月份的用戶輸入(例如2012 3)並輸出其中的天數,但是,它必須通過確定它是否爲閏年來完成這樣它就可以知道月份有多少天了,所以它不能預編程,它必須自行計算。並且當輸入無效月份(僅限1-12)或輸入負整數/小數時,它必須提示重新輸入。我不知道如何開始這個!計算一個月中的天數基於閏年?

我也開始否則我不會問,

的System.out.println( 「請輸入年份和月份:」);

if (stdin.hasNextInt()) { 
     yes = true; 
    int year = stdin.nextInt(); 
    int month = stdin.nextInt(); 
    } 
     else { 
      System.out.println("Invalid Input. ");} 

    if (yes = true); 

    } 
} 

我不知道如何得到它採取了兩個數字作爲單獨的INT(2012年3),以及如何,如果其無效或一年,如果其無效....

+6

我建議在開始你的任務,當你遇到一個簡潔的,具體的問題,詢問關於它的堆棧溢出。 – Vulcan 2013-03-01 00:54:31

回答

1

有拒絕一個月你必須檢查兩件事情告訴如果一年是閏年:

  1. 如果年份能被4整除但不能被100整除則是閏年。

  2. 如果年份可以被100整除,也可以被400整除,那麼它就是閏年。

-Code它uppppp

(還只是谷歌是ISH下一次 - >「如何判斷一個年份是閏年」)

1

讓我們寫一個函數,它的

公衆詮釋NUMBEROFDAYS(INT年,月整型){

大多數月份的年份和月份(1..12)數量,並返回給定月份的天數有天,每一個固定數量年,因此:

if (month==1||month==3||month==5||month==7|| 
    month==8||month==10||month==12) return 31; 
if (month==4||month==6||month==9||month==11) return 30; 

此時(如果該函數尚未返回),該月份爲2月份,或者該月份無效。讓要是下個月是無效的恢復明顯的無效值:

if (month!=2) return -1; 

現在,它變得有趣,因爲二月有閏年爲29天,28天否則。自1582年引入公曆年以來,一年的定義是4的倍數,但100年的倍數不是閏年,除非它們也是400的倍數(即1600,2000和2004年是閏年; 1900年和2003年沒有)。

if (year>1582) { 
if (month%4==0&&(month%100!=0||month%400==0)) return 29; else return 28; 
} 

在1582年之前,朱利安曆法有效。根據儒略曆,每年可以被4整除的是閏年。

else { 
//julian calendar 
if (month%4==0) return 29; else return 28; 
} 

現在代碼調用numberOfDays

int days; 
do { 
System.out.println("blah blah blah"); 
int year = stdin.nextInt(); 
int month = stdin.nextInt(); 
days = numberOfDays(year,month); 
} while (days<0);