实现万年历的条件
1.计算月份天数
2.计算年份天数
3.润年条件:能被4整除且不能被100整除,或者能被400整除
4.已知起始某年某月某日为星期几
5.计算星期
import com.sun.org.apache.regexp.internal.RE;
import java.util.Scanner;
public class allday {
public static int textDay(int year){
//以1999年为起始年份(1999.12.31为星期五)
//用户输入年份的那一年的总天数
int alldays = 0;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)){
//润年
alldays = 366;
}
//平年
else {
alldays = 365;
}
return alldays;
}
public static int getMonthDay(int year,int month){
//所选月份的天数
int days = 0;
switch (month){
//当月份为4,6,9,11的天数固定为30天
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
//当月份为1,3,5,7,8,,10的天数固定为31天
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
//2月份另外计算
case 2:
//润年
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)){
days = 29;
}
//平年
else {
days = 28;
}
break;
//当用户输入月份错误时报错
default:
System.out.println("输入的月份不合格");
break;
}
return days;
}
public static int countDay(int year,int month,int day){
//记录year与1999距离总天数
int alldays = 0;
for (int i = 1; i < (year-1999-1) ; i++) {
alldays += textDay(year);
}
return alldays;
}
public static int getWeekDay(int year,int month){
//剩余月份的总共天数
int totalmonthday = 0;
for (int i = 1; i < month; i++) {
totalmonthday += getMonthDay(year,month);
}
return totalmonthday;
}
public static int yearMonthDaytoYear(int year,int month ,int day){
//year month day距离1999的总共天数
int otherday = 0;
//总共天数=(year-1)与1999的距离天数+当年剩余月份的总共天数+day的天数
otherday = countDay(year,month,day) + getWeekDay(year,month) +day;
return otherday;
}
//计算星期的方法
public static int printWeek(int year,int month,int day){
//星期几
int week = 0;
//星期几= ((((year-1)-1999)的天数+当年year的month的总天数+day)+5)%7
week = (yearMonthDaytoYear(year,month,day)+5)%7;
return week;
}
//日历排版方法,每个月1号是星期几就是对应由(日开始的日历就是日一二三四五六的顺序排版)的1号是由星期几开始,规律看下图
public static void printDate(int year,int month){
System.out.println("日\t一\t二\t三\t四\t五\t六");
//获取year.month.1的是星期几
int week = printWeek(year,month,1);
int count = 0;
for (int i = 0; i < week ; i++) {
count++;
System.out.print("\t");
}
int printday = getMonthDay(year,month);
for (int i = 1; i <= printday ; i++) {
count++;
System.out.print(i+"\t");
if (count%7 == 0){
System.out.println();
}
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("请输入年份");
int year = input.nextInt();
System.out.println("请输入月份");
int month = input.nextInt();
printDate(year,month);
}
}
星期的公式:
已知1999.12.31为星期五
week = ((((当年year-1)-1999)的总天数+当年year的month的总天数+day)+5)%7
日历前面空格的规律:
前面输入空格的规律为1号为星期n,前面就要有n个空格的效果
效果图: