2016-12-10 7 views
-2

Dateクラスをインポートせずに日付を計算するコードを記述する必要があります。 まず、有効な日付 を入力する必要があり、何をすべきか分からない。日付のクラスをインポートしないJavaの日付コード

 Scanner scan = new Scanner(System.in); 
    int day,month,year,february; 
    System.out.println("please enter three nubers that represent original date"); 
    day = scan.nextInt(); 
    month = scan.nextInt(); 
    year = scan.nextInt(); 
    if(year <= 0 || day <= 0 || month <= 0 || month > 12){ 
     System.out.println("The original date is " + day + "/" + month + "/" + year + 
     " is invalid"); 
    } 
    if (year%100 == 0 || year % 4 != 0) 
     february = 28; 
     else if (day>28) 
     System.out.println("invalid date"); 
     else if(year%400 == 0) 
     february = 29; 
     else if(day>29) 
      System.out.println("invalid date"); 
     else if(year%4 == 0) 
     february = 29; 
     else if(day>29) 
      System.out.println("invalid date"); 
+0

あなたの質問は何ですか?また、宿題の日付計算はすでに何度も処理されています。投稿の前にスタックオーバーフローを検索してください。 –

答えて

0

あなたは、毎月の最大日数を知る必要があります。最大の課題は2月ではない月に対処することです。一行ごとに説明するのは難しいので、私はそのコードがそれ自体について話すことを望んでいます。 私はコードをもっと短くすることができましたが、私はこれをあたかもそのようにしておき、あなたのコードによく一致します。 http://www.timeanddate.com/date/leapyear.html

//january = daysInMonth[0], february = daysInMonth[1] 
    int daysInMonth[] = new int[] 
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 
    int year = 1800; 
    int day = 30; 
    int month = 3; 
    if (month != 2) //Month is not February 
    { 
    int daysInEnteredMonth = daysInMonth[month - 1]; 
    System.out.println("Days in entered month " + daysInEnteredMonth); 
    if (day > daysInEnteredMonth) 
    { 
     System.out.println("invalid date"); 
    } 
    } 
    else 
    { 
    // Month is February 
    if (year % 4 != 0) 
    { 
     daysInMonth[1] = 28; 
    } 
    else if (year % 400 == 0) 
    { 
     daysInMonth[1] = 29; 
    } 
    else if (year % 100 == 0) 
    { 
     daysInMonth[1] = 28; 
    } 
    else //year is divisible by 4 
    { 
     daysInMonth[1] = 29; 
    } 
    //Do the comparison 
    int daysInEnteredMonth = daysInMonth[month - 1]; 
    System.out.println("Days in entered month " + daysInEnteredMonth); 
    if (day > daysInEnteredMonth) 
    { 
     System.out.println("invalid date"); 
    } 
    } 
+0

あなたの閏年の方法は確実ですか? 2000年(閏年)と2100年(閏年なし) –

+0

Chrstoph-Tobias Schenkeを指摘していただきありがとうございます。私は間違ってアルゴリズムを誤っていた。コードが更新され、ルールが追加されました。 – ProgrammersBlock

0

それは2月29日(うるう年、うるう日)に今年の場合は指定された年でチェックする簡単な方法。

private boolean isLeapYear(int year) { 
    //in general we have every 4 years an aditional day in february 
    if (year % 100 == 0) { 
     //... unless its a full century (1900,2000,2100) then it also must be divisible by 400 
     if (year % 400 == 0) { 
      return true; 
     } 
    } else if (year % 4 == 0) { 
     //every 4 years 
     return true; 
    } 

    //no leap year by default 
    return false; 
} 
関連する問題