2016-10-05 60 views
0

好吧,所以我正在嘗試製作一個日曆,以便用戶輸入第一個星期一是該月的那一天以及該月的總天數。在一週的指定日期開始日曆

輸出應該是這個樣子: (見鏈接的圖像)

IMAGE

這是我到目前爲止有:

int daysLeft = numDays; 

for(int week = 1; week <= 5; week++) 
    { 
     if(daysLeft > 1) 
     { 
      for(int day = 1; day <= numDays; day++) 
      { 
       if((day % 7) == 1) , if the day % 7 (a week) is equal to 1 then go to the next line 
       { 
       System.out.println(); 
       } 

       System.out.print(day); 
       daysLeft--; 
      } 
     } 
    } 

我想用嵌套for循環爲此,我知道它可以完成,我知道我可以使用日曆類,但我正在學習,並希望使用for循環。所以,上面的代碼工作如果第一個星期一也是拳頭的一天。

基於上述信息,我怎樣才能使用for循環來改變月份的起始位置?

編輯 忽略閏年。

+0

您也不必擔心閏年(二月可能有28或29天)。 –

+0

@TimBiegeleisen爲了簡單起見,我們忽略了閏年。 – MicrosoftDave

回答

1

1)你也許並不需要一個嵌套的for循環,你的外for循環沒有采取任何實際

2)我還是有點AB不清楚您的要求,這是我能想出的最好和我覺得它很好,你描述的內容:

public static void printCalendar(int monday, int numDays) { 
    if (monday > 7 || monday < 1) throw new IllegalArgumentException("Invalid monday."); 
    if (numDays > 31 || numDays < 1 || numDays < monday) throw new IllegalArgumentException("Invalid numDays."); 

    System.out.print("Mon\t"); 
    System.out.print("Tue\t"); 
    System.out.print("Wed\t"); 
    System.out.print("Thur\t"); 
    System.out.print("Fri\t"); 
    System.out.print("Sat\t"); 
    System.out.print("Sun\t"); 
    System.out.println(); 

    int padding = (7 - (monday - 1)) % 7; 

    for (int i = 0; i < padding; i++) { 
     System.out.print(" \t"); 
    } 

    for (int day = 1; day <= numDays; day++) { 
     if ((padding + day) % 7 == 0) 
      System.out.println(day + "\t"); 
     else 
      System.out.print(day + "\t"); 
    } 
} 

sample output with printCalendar(3, 31);

+0

這就是我一直在尋找的!非常聰明,謝謝。 – MicrosoftDave

相關問題