package com.calender.java;
import java.util.Scanner;
public class Calendar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int year = sc.nextInt();
System.out.println("请输入月份");
int month = sc.nextInt();
boolean flag = isLeapYear(year);
//System.out.println(flag);
int monthSumDay = getMonthDay(month, flag);
//System.out.println(monthDay);
int week = getWeek(year, month);
//System.out.println(week);
print(year, month);
formPrint(monthSumDay,week);
}
//输出表头
public static void print(int year, int month) {
System.out.println("\t" + "\t" + "<" + year + "年" + month + "月" + ">");
System.out.println("星期日" + "\t" + "星期一" + "\t" + "星期二" + "\t" + "星期三" +
"\t" + "星期四" + "\t" + "星期五" + "\t" + "星期六");
}
//判断是否是闰年
public static boolean isLeapYear(int year) {
boolean flag = false;
if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
flag = true;
}
return flag;
}
//判断某年某月的第一天是星期几(由于这个算法有问题,导致日历输入有一点问题)
public static int getWeek(int year, int month) {
int week = 0;
int realYear = (year % 10) + (year / 10 % 10) * 10;
//System.out.println(realYear);
if(month == 1) {
month = 13;
} else if(month == 2) {
month = 14;
}
week = realYear + realYear / 4 + 20 / 4 - 2 * 20
+ (26 * (month + 1)) / 10;
week %= 7;
return week;
}
//给每个月份赋值
public static int getMonthDay(int month, boolean flag) {
int[] arrMonth = {0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(flag == true) {
arrMonth[2] = 29;
} if(flag == false) {//用==号
arrMonth[2] = 28;
}
return arrMonth[month];
}
public static void formPrint(int monthSumDay, int week) {
for(int i = 0; i < week; i++) {
System.out.print("\t");
}
for(int i = 1; i <= monthSumDay; i++) {
System.out.print(i + "\t");
if((i + week) % 7 == 0) {
System.out.println();
}
}
}
}
|
-
结果.PNG
(7.68 KB, 下载次数: 14)
运行结果
|