问题:输入 年 - 月 打印出该月的日历
例如 2019-12
公式:
计算年月日是星期几 如 2019-11-1是星期几
公式:int week=(year-1+(year-1)/4-(year-1)/100+(year-1)/400+days)%7;
Java代码实现:
import java.util.Scanner;
public class Ecoh {
/*
* 给定年月如:2019,11,计算这个月有多少天
* 闰年 这一年被四百整除or能被4整除但是不能被100整除
*/
public static int getMonthDay(int year,int month) {
int days=0;
switch(month) {
case 4:
case 6:
case 9:
case 11:
days =30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days=31;
break;
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 getYearDays(int year,int month,int day) {
int days=0;
for(int i=1;i<month;i++) {
days+=getMonthDay(year,i);
}
days+=day;
return days;
}
/*计算年月日是星期几 如 2019-11-1是星期几
*公式:int week=(year-1+(year-1)/4-(year-1)/100+(year-1)/400+days)%7;
*/
public static int getWeek(int year,int month,int day) {
int days= getYearDays(year,month,day); //调用getYearDays
int week=(year-1+(year-1)/4-(year-1)/100+(year-1)/400+days)%7; //days-----通过调用getYearDays获得
return week;
}
//星期几就是几个空
public static void printCalendar(int year ,int month) {
if(month<=3&&month>=1) System.out.println("Spring");
else if(month<=6&&month>=3) System.out.println("Summer");
else if(month<=9&&month>=6) System.out.println("Aumutn");
else System.out.println("Winter");
System.out.println(" 日\t一\t二\t三\t四\t五\t六 ");
System.out.println();
int flag=0;
int week= getWeek(year,month,1); //求1号是星期几
for(int i=0;i<week;i++) {
flag++;
System.out. print("\t");
}
int count=flag;
int monthday= getMonthDay(year,month);
for(int j=1;j<=monthday;j++) {
System.out.print(j+"\t");
count++;
if(count%7==0) {
System.out.println("\n");
}
}
}
public static void main(String[] args) {
/*TODO Auto-generated method stub 给定年月日,这天是这一年的第多少天
int yeardays = getYearDays(2019,4,5);
System.out.println(yeardays);
// TODO Auto-generated method stub 给定年月,这个月有多少天
int monthdays = getMonthDay(2018,8);
System.out.println(monthdays);
// TODO Auto-generated method stub
int weeks = getWeek(2019,5,5);
System.out.println(weeks);
System.out.println("例如:2019按“回车”5");
Scanner in=new Scanner(System.in);
Scanner sc=new Scanner(System.in);
printCalendar(in.nextInt(),sc.nextInt());
*/
Scanner s=new Scanner (System.in);
while(true) {
System.out.println("\n");
String s1=s.nextLine();
String []data=s1.split("-"); //split:对字符串进行分割
printCalendar(new Integer(data[0]),new Integer(data[1]));
}
}
}
来源:CSDN
作者:划过一道痕
链接:https://blog.csdn.net/weixin_44115126/article/details/103600275