直接上代码
是否有更简洁的代码
package ch3choose.exer21;/*
* 孤鸿
* 2023/5/16
*/
import java.util.Scanner;
public class Exer21 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter year :(e.g., 2012: "); //输入年份
int year=input.nextInt();
while (true){ // 判断输入的年份是否在有效的年份中,默认取4位的年份作为合法年份
if(year>0&&Integer.toString(year).length()!=4){
System.out.print("请输入正确的年份:");
year=input.nextInt();
}
else{
break;
}
}
System.out.print("Enter month: 1-12: "); //输入月份
int month=input.nextInt();
while (true){//判断输入的月份是否合法
if(month<=0||month>12){
System.out.print("输入月份有误,请重新输入:");
month=input.nextInt();
}
else{
break;
}
}
System.out.print("Enter the day of the month :1-31");
//判断当月有多少天
int max=0;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
max = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
max = 30;
} else if (month == 2) {
if (year % 400 == 0 || ((year % 100 != 0) && (year % 4 == 0))) {
max = 29;
} else {
max = 28;
}
}
if(month==1||month==2){
month+=12;
year-=1;
}
int day=input.nextInt(); //输入日期
while(true){ //判断输入的日期是否合法
if(day>0&&day<=max){
break;
}
else{
System.out.println("日期输入有误,请重新输入:");
day=input.nextInt();
}
}
int j=year/100;
int k=year%100;
int h=(day+((26*(month+1))/10)+k+k/4+j/4+5*j)%7;
System.out.println("Day of the week is "+weekday.values()[h]); //获取枚举中对应的星期几
}
public enum weekday{
Saturday,Sunday, Monday, Tuesday, Wednesday, Thursday, Friday;
}
}