JAVA控制台输入年月打印万年历
# Jpublic static void main(String[] args) {
int sum=0;
int year=0;
int month=0;
int monthCount=0;
Scanner sc=new Scanner(System.in);
while(true) {
System.out.println("请输入年份");
if(sc.hasNextInt()) {
year=sc.nextInt();
if(year>=1900&&year<=2021) {
break;
}
}else {
System.out.println("年份格式不对,重新输入");
sc.nextLine();
}
}
while(true) {
System.out.println("请输入月份");
if(sc.hasNextInt()) {
month=sc.nextInt();
if(month>=1&&month<=12) {
break;
}else {
System.out.println("月份格式不对,请重新输入");
sc.nextLine();
}
}
}
for (int i = 1900; i < year; i++) {
if((i%4==0&&i%100!=0)||(i%400==0)) {
sum+=366;
}else {
sum+=365;
}
}
sum++;
for (int i = 1; i < month; i++) {
if(i==4||i==6||i==9||i==11) {
sum+=30;
}else if(i==2) {
if((year%4==0&&year%100!=0)||(year%400==0)) {
sum+=29;
}else {
sum+=28;
}
}else {
sum+=31;
}
}
switch(month) {
case 4:
case 6:
case 9:
case 11:{
monthCount=30;
}break;
case 2:{
if((year%4==0&&year%100!=0)||(year%400==0)) {
monthCount=29;
}else {
monthCount=28;
}
}break;
default:{
monthCount=31;
}
}
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
int weekDays=sum%7;
for (int i = 1; i <= weekDays; i++) {
System.out.print("\t");
}
for (int i = 1; i <= monthCount; i++) {
if(sum%7==6) {
System.out.print(i+"\n");
}else {
System.out.print(i+"\t");
}
sum++;
}
sc.close();
}