控制台输入年月日,输出该日期为该年的第多少天?

控制台输入年月日,输出该日期为该年的第多少天?(java基础开发只用if..else if..和switch...case)

方法一:只用if..else

System.out.print("请输入年份:");
        int year=input.nextInt();
        int  sum = 0;
        if(year>=1900&&year<=2099){//较验年份
            System.out.print("请输入月份:");
            int mouth = input.nextInt();
            boolean isLeapYear = (year%4==0 && year%100!=0)||year%400==0;//判断闰年
            if(mouth<=12&&mouth>=1) {//校验月份
                System.out.print("请输入日:");
                int day = input.nextInt();
                int cheakDay = 0;
                for(int i = 1;i<=mouth;i++){
                    if(i == 4 || i == 6 || i == 9 || i == 10 || i == 11){
                        sum += 30;
                        cheakDay = 30;
                    }else if(isLeapYear && i == 2){
                        sum += 29;
                        cheakDay = 29;
                    }else if(!isLeapYear && i == 2){
                        sum += 28;
                        cheakDay = 28;
                    }else {
                        sum += 31;
                        cheakDay = 31;
                    }
                }
               if(day>0&&day<=cheakDay){//校验日
                   sum = (sum+day)-cheakDay;
                   System.out.println(year+"年"+mouth+"月"+day+"日,在该年中的第"+sum+"天");
               }else {
                   System.out.println("输入正确的日");
               }
            }else{
                System.out.println("请输入正确的月份");
            }
        }else{
            System.out.println("请输入正确的年份");
        }

方法二:加入switch...case

int year, month, day;
System.out.println("请输入4位年");
year = input.nextInt();
System.out.println("请输入月");
month = input.nextInt();
System.out.println("请输入日");
day = input.nextInt();
if (year < 1900 || year > 2099) {
    System.out.println("请输入正确的年,在1900-2099之间");
} else if (month < 1 || month > 12) {
    System.out.println("请输入正确的月,在1-12之间");
} else {
    boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;//判断闰年
    int days = 31;
    switch (month) {
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        case 2:
            days = isLeapYear ? 29 : 28;
            break;
    }
    if (day < 1 || day > days) {
        System.out.println("请输入1至" + days + "之间的天数");
    } else {
        int total = day;
        for (int i = 1; i < month; i++) {
            days = 31;
            switch (i) {
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;
                    break;
                case 2:
                    days = isLeapYear ? 29 : 28;
                    break;
            }
            total += days;
        }
        String info = MessageFormat.format("{0}年{1}月{2}日是{0}年的第{3}天", year, month, day, total);
        System.out.println(info);
    }


}
原文地址:https://www.cnblogs.com/chenyyStudy/p/12907213.html