【每天一道编程系列-2018.1.31】(Ans)

【题目描述】

Enter a certain day of a year to determine which day is it of the year? 



【题目翻译】

输入某年某月某日,判断这一天是这一年的第几天? 



【解题思路】

以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。



【本题答案】


import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Description:<br> 输入某年某月某日,判断这一天是这一年的第几天?
 * <br>
 * Remark:<br>
 * <br>
 * Date:2018/1/31
 *
 * @author yesr
 * @version 0.0.1
 */
public class Test0131 {
    private static boolean isLeapYear(int y){
        return (y % 4 == 0 && y % 100 != 100) || y % 400 == 0;
    }

    private static int sumDays(int y, int m, int d){
        int[] MonthDays = {31,28,31,30,31,30,31,31,30,31,30,31};
        if(isLeapYear(y)) MonthDays[1] = 29;
        int ans = 0;
        for(int i=0; i<m-1; i++){
            ans = ans + MonthDays[i];
        }
        return ans + d;
    }

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String in = null;
        try {
            System.out.println("请输入年月日,例如:2014-01-01");
            in = br.readLine();
        } catch (Exception e) {
            System.out.println("格式错误");
        }
        assert in != null;
        int y = Integer.parseInt(in.substring(0, in.indexOf('-')));
        int m = Integer.parseInt(in.substring(in.indexOf('-') + 1, in.lastIndexOf('-')));
        int d = Integer.parseInt(in.substring(in.lastIndexOf('-') + 1));
        while (!isLeapYear(y)) {
            if ((d > 31)||(m > 12)||(d == 29)||(d == 30)||(d == 31)) {
                System.out.print("日期不存在,请输入正确日期");
                break;
            } else {
                System.out.println(sumDays(y, m, d));
                break;
            }
        }
        while (isLeapYear(y)) {
            if ((d > 31)||(m > 12)||(m == 2)&&(d == 30)||(m == 2)&&(d == 31)) {
                System.out.println("日期不存在,请输入正确日期");
                break;
            } else {
                System.out.println(sumDays(y, m, d));
                break;
            }
        }

    }
}



【运行结果】











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值