Java_万年历(简单)

1、方法,需要一个年份,一个月份。然后在控制台输出日历

 1 // 输入一个年份和一个月份显示日历
 2     public static void printCalendar(int year, int month) {
 3         // 转换日期
 4         Calendar calendar = Calendar.getInstance();
 5         // 找到月份第一天
 6         calendar.set(year, month-1, 1);
 7         // 找到第一天是周几  1 周日 2 周二
 8         int week = calendar.get(Calendar.DAY_OF_WEEK);
 9         //System.out.println("week: "+week);
10         // 获取最大日期
11         int dayMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
12         // 循环输出
13         System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t");
14         // 若第一天不为周日
15         if(week != 1) {
16             // 判断01是周几  空格
17             for(int j = 1;j < week;j++) {
18                 System.out.print(" \t");
19             }
20         }
21         // 循环
22         for (int i = 1; i <= dayMax; i++) {
23             // 找到第 i 天  
24             calendar.set(year, month-1, i);
25             // 第  i 天是周几
26             int wek = calendar.get(Calendar.DAY_OF_WEEK);
27             System.out.print(i + "\t");
28             // 周六回车
29             if ( wek == 7) {
30                 System.out.println();
31             }
32             
33         }
34     }

2、MainTest测试类

 1 public static void main(String[] args) {
 2         // 万年历测试类
 3         Scanner scanner = new Scanner(System.in);
 4         boolean isTrue = true;
 5         while(isTrue) {
 6             System.out.println("-------------万年历------------");
 7             System.out.println("1、查看日历");
 8             System.out.println("0、退出");
 9             int key = scanner.nextInt();
10             switch (key) {
11             case 1:
12                 System.out.println("请输入年份:");
13                 int year = scanner.nextInt();
14                 System.out.println("请输入月份:");
15                 int month = scanner.nextInt();
16                 PerpetualCalendar.printCalendar(year, month);
17                 System.out.println();
18                 break;
19             default:
20                 isTrue = false;
21                 break;
22             }
23         }
24         System.out.println("已退出系统...");
25     }

3、运行结果:

 

  有帮助,就点个推荐吧,让更多人看到

猜你喜欢

转载自www.cnblogs.com/dongxiucai/p/9467154.html