泽勒的一致性

该Java程序从用户处获取年、月、日输入,验证输入的有效性,然后计算并输出对应日期是星期几。程序使用Scanner类读取输入,通过条件判断处理不同月份的天数,考虑了闰年的规则,并用枚举类型表示星期。
摘要由CSDN通过智能技术生成

直接上代码

是否有更简洁的代码

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值