输入年份,打印日历
Posted ASMLearner
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了输入年份,打印日历相关的知识,希望对你有一定的参考价值。
1 //: 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.BufferedReader; 5 public class Calendar2 { 6 static int year; 7 static int weekDay; 8 public static void main(String[] args) throws IOException { 9 System.out.println("Please input Year: "); 10 InputStreamReader ir = new InputStreamReader(System.in); 11 BufferedReader in = new BufferedReader(ir); 12 String s = in.readLine(); 13 year = Integer.parseInt(s); 14 weekDay = (int)firstDayOfYear(year); 15 System.out.println(" "+year+"年日历"); 16 System.out.println("============================================================="); 17 for (int i=1;i<=12;i++){ 18 System.out.println(); 19 printMonth(i); 20 System.out.println(); 21 System.out.println("=============================================================="); 22 } 23 } 24 public static void printMonth(int m){ 25 printHead(m); 26 int day = dayOfMonth(m); 27 for (int i=1;i<=day;i++){ 28 if(i<10){ 29 System.out.print("\\t "+i); 30 } 31 else System.out.print("\\t"+i); 32 weekDay = (weekDay+1)%7; 33 if(weekDay==0){ 34 System.out.println(); 35 System.out.print("\\t\\t\\t\\t \\t"); 36 } 37 } 38 } 39 public static int dayOfMonth(int m){ 40 switch(m){ 41 case 1: 42 case 3: 43 case 5: 44 case 7: 45 case 8: 46 case 10: 47 case 12: 48 return 31; 49 case 4: 50 case 6: 51 case 9: 52 case 11: 53 return 30; 54 case 2: 55 if (isLeapYear(year)) return 29; 56 else return 28; 57 58 } 59 return 0; 60 } 61 public static void printHead(int m){ 62 System.out.println(m+"\\t"+"月"+"\\t"+"\\t\\t\\t\\t"+"日"+"\\t"+"一"+"\\t"+"二"+"\\t"+"三"+"\\t"+"四"+"\\t"+"五"+"\\t"+"六"); 63 System.out.print("\\t\\t\\t\\t \\t"); 64 for(int i=1;i<=weekDay;i++){ 65 System.out.print("\\t "); 66 } 67 } 68 public static long firstDayOfYear(int y){ 69 long n; 70 n=y*365; 71 for(int i=1;i<=year;i++){ 72 if (isLeapYear(i)){ 73 n+=1; 74 } 75 } 76 return n%7; 77 } 78 public static boolean isLeapYear(int i){ 79 return (i%4==0 && i%100!=0) || i%400==0; 80 } 81 } 82 ///:~
目前发现计算第一天星期几(weekDay)有问题,比如2000年,未找到解决方法。
以上是关于输入年份,打印日历的主要内容,如果未能解决你的问题,请参考以下文章