java实现输入年份月份,自动生成日历
下面展示一些 内联代码片
。
// 导入Scanner包进行程序交互
import java.util.Scanner;
// An highlighted block
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("请输入年份");
int year=sc.nextInt();
System.out.println("请输入月份");
int month=sc.nextInt();
int totaldays=totalDays(year, month);
//System.out.println("距离1900-1-1共有"+totaldays+"天");
System.out.println("星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日");
int week=totaldays%7+1;
if(week==1){
week=0;
}
//循环输出当前月份之前的空格距离
for(int i=1;i<week;i++){
System.out.print("\t");
}
int days=getMonthDays(year, month);
for(int i=1; i<=days;i++){
System.out.print(i+"\t");
if((i+totaldays)%7==0){
System.out.println();
}
}
}
/**
* 判断年份是否为闰年,如果是则返回true,如果不是则返回false
* @param year
* @return 是否为闰年
*/
public static boolean isR(int year){
//判断是否为闰年
if(year%4==0&&year%100!=0||year%400==0){
//是闰年
return true;
}else{
//不是闰年
return false;
}
}
//获取一年有多少天
public static int getYearDays(int year){
//用于接收返回天数
int yearDays;
//判断是否为闰年
if(isR(year)){
yearDays=366;
}else{
yearDays=367;
}
//返回结果天数
return yearDays;
}
//获取指定某年月拥有得天数
public static int getMonthDays(int year,int month){
//获取30天月份
switch (month) {
case 4:
case 6:
case 9:
case 11:
return 30;
//获取2月月份天数,调用上面方法,若满足条件则返回29天,否则返回28天
case 2:
if(isR(year)){
return 29;
}else{
return 28;
}
//若都不满足条件,则返回31天
default:
return 31;
}
}
public static int totalDays(int year,int month){
int totaldays=0;
for(int i=1900;i<year;i++){
totaldays+=getYearDays(i);
}
for(int j=1;j<month;j++){
totaldays+=getMonthDays(year,j);
}
return totaldays;
}