計算日期到天數轉換

題目描述

根據輸入的日期,計算是這一年的第幾天。。
詳細描述:
輸入某年某月某日,判斷這一天是這一年的第幾天?。

輸入描述

輸入三行,分別是年,月,日

輸出描述

成功:返回outDay輸出計算後的第幾天; 失敗:返回-1

輸入例子

2012
12
31

輸出例子

366

算法實現

import java.util.Scanner;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            int year = scanner.nextInt();
            int month = scanner.nextInt();
            int day = scanner.nextInt();

            System.out.println(calculate(year, month, day));
        }

        scanner.close();
    }

    private static int calculate(int year, int month, int day) {

        int[] dayOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        // 若是是閏年
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            dayOfMonth[1] = 29;
        }

        if (month < 1 || month > 12 || day < 1 || day > dayOfMonth[month - 1]) {
            return -1;
        }


        for (int i = 0; i < month - 1; i++) {
            day += dayOfMonth[i];
        }

        return day;
    }
}
相關文章
相關標籤/搜索