题目描述:从键盘输入1900年之后的任意的某年、某月,输出该月的日历
(已知1900年1月1日为星期一) 示例如下:
星期日 星期一 星期二 星期三 星期四 星期五 星期六
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
……
代码展示:
package com.zijie.Homework;
import java.util.Scanner;
/**
* 你的日积月累 终会成为别人的望尘莫及
*/
//日历:输入年份和月份即可得到当前月日历
public class work3 {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
int year = a.nextInt(); //接收输入的年份
int month = a.nextInt(); //接收输入的月份
int monthday = themonthday(month, year); //调用themonthday得到本月天数
int xingqiji = xingqiji(year, month); //调用xingqiji得到本月第一天星期几
int day = 8 - xingqiji; //第2——4行首元素日期
System.out.println(monthday); //调试1
System.out.println(xingqiji); //调试2
System.out.println("星期日 星期一 星期二 星期三 星期四 星期五 星期六 ");
for (int i = 0; i < xingqiji; i++) {
System.out.print(" ");
}//第一行空格
for (int i = 1; i <= 7 - xingqiji; i++) {
System.out.print(i + " ");
}//第1行日期
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(day + " ");
day++;
}
System.out.println();
}//第2——4行日期
for (int i = 29 - xingqiji; i <= monthday; i++) {
System.out.print(i + " ");
}
//最后一行日期
}
public static int xingqiji(int year, int month) {
int yearday = 0;//之前所有年份有多少天
int monthday = 0;//今年之前所有月份有多少天
for (int i = 1900; i < year; i++) {
if (i % 4 == 0 && i % 400 != 0)
yearday += 366;
else yearday += 365;
}//求yearday
for (int i = 1; i < month; i++) {
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
monthday += 31;
else if (i == 2 && !(year % 4 == 0 && year % 400 != 0))
monthday += 28;
else if (i == 2 && (year % 4 == 0 && year % 400 != 0))
monthday += 29;
else
monthday += 30;
}//求monthday
System.out.println(yearday);//调试3
System.out.println(monthday);//调试4
return (yearday + monthday+1) % 7;
}
public static int themonthday(int month, int year) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
return 31;
if (month == 2 && !(year % 4 == 0 && year % 400 != 0))
return 28;
if (month == 2 && (year % 4 == 0 && year % 400 != 0))
return 29;
else
return 30;
}
//方法体类似于求monthday
}