由java编写的万年历
- package perpetualCalendar;
- import java.util.Scanner;
- public class Part01 {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入年:");
- int year = scanner.nextInt();
- System.out.println("请输入月:");
- int month = scanner.nextInt();
- //计算输入月份有几天
- int monthDay = countMonthDay(year,month);
- //距离1900年1月1日的总天数
- int day;
- day = countDay(year);
- //输入月份距离输入年份的1月1日的总天数
- int day2;
- day2 = countCurrentYear(year, month);
- //总天数
- int totalDay;
- totalDay = day + day2;
- //输入月的第一的星期数
- int week;
- week = (totalDay + 1)%7;
- System.out.print("星期日"+'\t'+"星期一"+'\t'+"星期二"+'\t'+"星期三"+'\t'+"星期四"+'\t'
- +"星期五"+'\t'+"星期六"+'\n');
- for(int i=0;i<week;i++)
- System.out.print('\t');
- for(int i = 1;i<=monthDay;i++) {
- if(week%7 == 0)
- System.out.println();
- System.out.print(i);
- System.out.print('\t');
- week ++;
- }
- }
- //判断是否为闰年
- static boolean testLeapYear(int year) {
- if((year%4 == 0&&year%100 == 0) || year%400 == 0)
- return true;
- else
- return false;
- }
- //计算当月天数
- static int countMonthDay(int year,int month) {
- if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
- month == 10 || month == 12) {
- return 31;
- }else if(month == 4 || month == 6 || month == 9 || month == 11) {
- return 30;
- }else {
- if(testLeapYear(year))
- return 29;
- else
- return 28;
- }
- }
- //计算输入年份距离1900年1月1日的总天数
- static int countDay(int year) {
- int day = 0;
- for(int i=1900;i<year;i++) {
- if(testLeapYear(i))
- day += 366;
- else
- day += 365;
- }
- return day;
- }
- //计算输入月份距离输入年份的1月1日的总天数
- static int countCurrentYear(int year,int month) {
- int day = 0;
- for(;month!=1;month--) {
- day += countMonthDay(year,month);
- }
- return day;
- }
- }