//25. 萬年歷(實現(xiàn)從鍵盤輸入1900年之后的任意的某年、某月,輸出該月的日歷)
import java.util.Scanner;
public class Calendar{
public static void main(String[] args){
//顯示日歷
// 1、對應(yīng)月份的天數(shù)
// ① 1、3、5、7、8、10、12月份? 31天
// ② 4、6、9、11 ? 30天
// ③ 2 ? 28天或29天(待定)
// 2、對應(yīng)月份1號 是星期幾
// ① 1900年 1月 1日 星期1?
// ② 指定日期的星期? 與1900年1月1日相差的天數(shù)%7+1 (1~7的范圍)
// ③ 相差天數(shù)=1900年與年份之間相差的天數(shù) + 年份到指定月份1號之前相差的天數(shù)
// 3、指定年份是平年還是閏年(確定二月 的天數(shù))
// ① 確定指定年份的2月有多少天
//接收用戶從控制臺輸入的數(shù)據(jù)
Scanner sc = new? Scanner(System.in);
System.out.println("請輸入年份(>=1900):");
int year = sc.nextInt();//獲取年份
System.out.println("請輸入月份[1-12]:");
int month = sc.nextInt();//獲取月份
//1、對應(yīng)月份的天數(shù)
int days = 28;
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
days = 31;
}else if(month==4||month==6||month==9||month==11){
days = 30;
}else{
if(year%400==0||(year%4==0&&year%100!=0)){//判斷閏年的情況
days = 29;
}
}
//2、相差天數(shù)
int yDays = 0;//統(tǒng)計兩個年份之間相差的天數(shù)
for(int y = 1900;y<year;y++){
if(year%400==0||(year%4==0&&year%100!=0)){//判斷閏年的情況
yDays += 366;
}else{
yDays += 365;
}
}
int mDays = 0;//指定年份1月1日,到指定月份1日相差的天數(shù)
for(int m = 1;m<month;m++){
if(m==1||m==3||m==5||m==7||m==8||m==10||m==12){
mDays += 31;
}else if(m==4||m==6||m==9||m==11){
mDays += 30;
}else{
if(year%400==0||(year%4==0&&year%100!=0)){//判斷閏年的情況
mDays += 29;
}else{
mDays += 28;
}
}
}
int totalDays = yDays + mDays+1;//相差總天數(shù)
int week = totalDays%7+1;//指定月份1號 的星期
System.out.println("日\t一\t二\t三\t四\t五\t六");
//先根據(jù)星期 確定需要打印空位的 情況(week)
for(int i = 1;i<=week;i++){
if(i%7==0){
System.out.println(" \t");
}else{
System.out.print(" \t");
}
}
//可以打印對應(yīng)月份的天數(shù)(days)
for(int j = 1;j<=days;j++){
if((j+week)%7==0){
System.out.println(j+"\t");
}else{
System.out.print(j+"\t");
}
}
}
}