zl程序教程

您现在的位置是:首页 >  大数据

当前栏目

题三:根据输入的年月日,计算是今年的第几天

计算输入 根据 今年 年月日 第几天
2023-09-11 14:19:26 时间

只要输入的地方都应该有合法检测,还有什么异常处理了,最好的当然是加上,不加的话主要看你怎么说服面试官让你不加也可以。

免责声明:注意我就是随手一写,对算法效率有要求的慎用

import java.util.Scanner;

/**
 * 3、输入年月日 输出这是今年第几天:
 Input the year:
 Input the month:
 Input  the day:
 2011:4:26时今年第116天。
 */
public class Test3 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Input the year:");
        int year = s.nextInt();
        System.out.println("Input the month:");
        int month = s.nextInt();
        System.out.println("Input the day:");
        int day = s.nextInt();
        System.out.println();

        if(!check(year,month,day)){
            System.out.println("非法输入,程序终止");
            return;
        }

        int count=0;
        switch (month-1){
            case(11): count+=30;
            case(10): count+=31;
            case(9): count+=30;
            case(8): count+=31;
            case(7): count+=31;
            case(6): count+=30;
            case(5): count+=31;
            case(4): count+=30;
            case(3): count+=31;
            case(2): {
                count+=28;
            }
            case(1): count+=31;
            default:
        }

        count+=day;

        if((year%4==0&&year%100!=0)||year%400==0){
      if(month>2)   count
++; } System.out.println(year+":"+month+":"+day+"是今年第"+count+"天。"); } public static boolean check(int year,int month,int day){ //检测年月日是否合法,这个自己写吧,年月日均为正数、月不可大于12,每个月有多少天,二月和闰年的关系 return true; } }