2015-04-22 42 views
2

注意DONOT標記複製它,我知道這是重複的問題,但我並沒有從it得到幫助。在一個月特定年份的天數不工作

我想計算特定年份的月份數。我讀this,但它是不是工作正常。我嘗試以下

public class NumOfDays { 
    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 
     System.out.print("Enter month: "); 
     int month = input.nextInt(); 
     System.out.print("Enter year: "); 
     int year = input.nextInt(); 

     Calendar mycal = new GregorianCalendar(year, month, 1); 

     System.out.println("Number of days are: " + mycal.getActualMaximum(Calendar.DAY_OF_MONTH)); 

    } 
} 

我的控制檯是

Enter month: 2 
Enter year: 2000 
Number of days are: 31 /// Wrong 

Enter month: 10 
Enter year: 1999 
Number of days are: 30 // Correct 

我知道有另外一種方式,即人工計算的話,但我想這樣做像上面。請讓我知道如果我做錯了什麼。

P.S:我正在使用JAVA-8。

+0

'mycal.get(Calendar.DAY_OF_MONTH)'不返回的天數 –

+1

這可能有助於解釋到底爲什麼這不是一個重複的,爲什麼您鏈接到的問題,沒有幫助你。 –

+0

@JigarJoshi謝謝,我更新了我的問題......問題仍然存在。 – Junaid

回答

7

2000年3月31天沒有?正如文檔所說,月份是基於零(http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#GregorianCalendar-int-int-int-

編輯:我很笨,我以爲你有一個月的天數計算出來。你需要使用getActualMaximum,而不是。 (http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#getActualMaximum-int-

+0

我更新了我的問題,但問題仍然存在...謝謝 – Junaid

+0

您仍然需要在您的月份減1,因爲您期望用戶從1開始,但Java從0開始 –

10

由於您使用的是Java 8我建議使用新的日期/時間API,java.time,特別是其YearMonth類:

YearMonth ym = YearMonth.of(2000, 2); 
System.out.println(ym.lengthOfMonth()); //29 as expected 
+2

比我的還好 – bowmore

+0

這個功能真的很好..謝謝.. – JGS

0

以下將肯定工作...

公共類NUMBEROFDAYS

{

公共靜態無效主要(字符串克[])

{

Scanner scanner = new Scanner(System.in);

int days,month,year,date; 

    System.out.println("enter year= "); 
    year=scanner.nextInt(); 

    System.out.println("enter month= "); 
    month=scanner.nextInt(); 

    date=1; 

    Calendar calendar=Calendar.getInstance(); 

    calendar.set(year, (month-1), date); 

    days=calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 

    System.out.println("max day= "+days); 
} 

}

相關問題