Core Java (六) 打印指定月份的日历

释放双眼,带上耳机,听听看~!

更改的core java的一个程序,利用了GregorianCalendar这个类。

输入年份以及月份,打印出指定月份的日历。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
1package com.xujin;
2
3import java.text.DateFormatSymbols;
4import java.util.Calendar;
5import java.util.GregorianCalendar;
6import java.util.Locale;
7import java.util.Scanner;
8
9public class Test {
10  static Scanner cin = new Scanner(System.in);
11  public static void main(String[] args){
12      Locale.setDefault(Locale.US);//设置为美国地区
13      System.out.print("Please input the year and month(like 1999 9):");       
14      int year = cin.nextInt();
15      int month = cin.nextInt();     
16      GregorianCalendar day = new GregorianCalendar();//从公元 4 年 3 月 1 日之后是准确的
17     
18      //将day设置为该月的第一天
19      day.set(Calendar.YEAR, year);
20      day.set(Calendar.MONTH, month - 1);    
21      day.set(Calendar.DAY_OF_MONTH, 1);
22     
23      int weekday = day.get(Calendar.DAY_OF_WEEK);       
24      int firstDayOfWeek = day.getFirstDayOfWeek();
25     
26      int indent = 0;
27      while(weekday != firstDayOfWeek){
28          indent++;
29          day.add(Calendar.DAY_OF_MONTH, -1);
30          weekday = day.get(Calendar.DAY_OF_WEEK);
31      }
32     
33      String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
34      do{
35          System.out.printf("%4s", weekdayNames[weekday]);
36          day.add(Calendar.DAY_OF_MONTH, 1);
37          weekday = day.get(Calendar.DAY_OF_WEEK);
38      }while(weekday != firstDayOfWeek);
39      System.out.println();
40     
41      for(int i = 0; i < indent; i++)
42          System.out.print("    ");
43      day.set(Calendar.DAY_OF_MONTH, 1);
44     
45      do{
46          int d = day.get(Calendar.DAY_OF_MONTH);
47          System.out.printf("%4s", d);
48         
49          day.add(Calendar.DAY_OF_MONTH, 1);
50          weekday = day.get(Calendar.DAY_OF_WEEK);
51         
52          if(weekday == firstDayOfWeek) System.out.println();
53      }while(month - 1 == day.get(Calendar.MONTH));
54     
55      if(weekday != firstDayOfWeek) System.out.println();
56  }
57 
58}
59

结果:

Core Java (六) 打印指定月份的日历

给TA打赏
共{{data.count}}人
人已打赏
安全技术

40种网页常用小技巧

2021-12-21 16:36:11

安全技术

从零搭建自己的SpringBoot后台框架(二十三)

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索