Java中输入年份打印日历

Posted ruukita

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中输入年份打印日历相关的知识,希望对你有一定的参考价值。

 1 import java.util.Calendar;
 2 import java.util.Scanner;
 3 public class Problem5 {
 4     public static void print_(int year,int firstDay,String[] month,int k,int[] days){
 5         if (firstDay>=7) firstDay-=7;//边界处理
 6         System.out.printf("\\t\\t%s%5d\\n",month[k],year);//打印年 月
 7         for (int i=1;i<=47;i++) System.out.print("-");//打印分割线
 8         System.out.printf("\\n%4s%7s%7s%7s%7s%7s%7s\\n","Sun","Mon","Tue","Wed","Thu","Fri","Sat");
 9         int key=1;
10         int line=1;
11         int n=firstDay+1;
12         int mod=(8-firstDay)%7;
13         while (line==1&firstDay>0&n>1) {//打印第一天前的空格
14             System.out.printf("%7s","");
15             n--;
16         }
17         a:while(true) {
18             for (int j=1;j<=7;j++,key++) {//一周七天的指针 key为月份中的天数指针
19                 if(key%7==mod|key==1) {//判断空格个数
20                     System.out.printf("%3d",key);
21                 }else System.out.printf("%7d", key);
22                 if (line==1&key==7-firstDay) {//在第一行打印7-n天
23                     key++;
24                     break;
25                 }
26                 if (key==days[k]) break a;
27             }
28             line++;
29             System.out.println();
30         }
31         System.out.println();
32         if (k!=11) print_(year,days[k]%7+firstDay,month,++k,days);//若k不等于12则继续调用方法
33     }
34     public static void main(String[] args) {
35         Scanner input=new Scanner(System.in);
36         System.out.print("Enter year: ");
37         int year=input.nextInt();
38         Calendar aCalendar=Calendar.getInstance();
39         aCalendar.set(year, 0 ,1);//year,1,1
40         int firstDay=aCalendar.get(Calendar.DAY_OF_WEEK)-1;//获得输入年份的第一天的星期数
41         System.out.println();//预存月份于数组 方便调用
42         String[] month= {"January","February","March","April","May","June","July","August","Sptember","October","November","December"};
43         int[] days= {31,28,31,30,31,30,31,31,30,31,30,31};//预存每月的天数
44         if ((year%4==0&year%100!=0)|year%400==0) days[1]=29;//闰年判断
45         print_(year,firstDay,month,0,days);//参数1:年份 参数2:第一天星期几 参数3:月份字符串 参数4:当前打印的月份-1 参数5:每个月的天数
46         input.close();
47     }
48 }

输出效果:技术分享图片

以上是关于Java中输入年份打印日历的主要内容,如果未能解决你的问题,请参考以下文章

输入年份和月份打印当月日历

输入年份和月份打印当月日历

Java实现打印日历的功能

从给定的月份/年份打印日历

Java打印日历表

输入年份,打印日历