【Java】按要求编程输出2018年日历

编程输出2018年日历。日历中要求含有月份,日期,星期(如星期一),然后统计并输出2018年日期的个位数的相应的星期恰好相同的总天数.

 1 import java.io.IOException;
 2 import java.util.Calendar;
 3 import java.util.GregorianCalendar;
 4 /*
 5  * 
 6  * @author 菠萝
 7  * 
 8  * 
 9  * 
10  */
11 public class HomeWork3
12 {
13     public static void main(String[] args) throws IOException 
14     {
15         CalendarPrinter cp = new CalendarPrinter();
16         cp.printCal();
17     }
18 }
19 
20 class CalendarPrinter {
21     int daynum = 0;
22     int sumday =0;
23 
24     private static final int monthCount = 12;
25 
26     public void printCal() 
27     {
28         
29         GregorianCalendar gCal = new GregorianCalendar();
30 
31         //确定年份
32         gCal.set(Calendar.YEAR, 2018);
33         for (int month = 0; month < monthCount; month++)
34         {
35             gCal.set(Calendar.MONTH, month);
36             printOut(gCal);
37         }
38     }
39 
40     private void printOut(Calendar cal) 
41     {
42         int month = cal.get(Calendar.MONTH);
43         System.out.println(month+1+"月");//打印日历前 打印几月
44         cal.set(Calendar.DAY_OF_MONTH, 1);
45 
46         int weekday = cal.get(Calendar.DAY_OF_WEEK);
47 
48         // 打印星期表头
49         System.out.println("  Mon Tue Wed Thu Fri Sat Sun");
50 
51         // 打印第一行
52         for (int i = Calendar.MONDAY; i < weekday; i++)
53             System.out.print("    ");
54         
55         do {
56             // 输出日期
57             int day = cal.get(Calendar.DAY_OF_MONTH);
58             if(weekday-1==0 && day % 10 == 7)
59                 daynum++;
60             if(weekday-1!=0 && day % 10 == weekday-1)
61             {
62                 daynum++;
63             }
64             if (day > 0)
65                 System.out.printf(" %3d",day);
66             else
67                 System.out.printf("%3d",day);
68             // 周日之后开始新的一行
69             if (weekday == Calendar.SUNDAY)
70                 System.out.println();
71              
72             cal.add(Calendar.DAY_OF_MONTH, 1);
73             weekday = cal.get(Calendar.DAY_OF_WEEK);
74 
75         } 
76         while (cal.get(Calendar.MONTH) == month);
77         
78         if (weekday != Calendar.MONDAY)
79             System.out.println();
80         sumday += daynum;
81         if (month+1 == 12)
82         System.out.println("2018年日期尾数与星期相同的有"+daynum+"天");
83     }
84     
85 }

 

posted @ 2018-04-20 16:09  ieblYang  阅读(1942)  评论(0编辑  收藏  举报