Java - Switch-case 計算X年X月X日為第X年第幾天

By sunwc 2023-03-17 Practice

思路:越下面的 case 被執行的機率越高,因此要從最下面的 case 1 倒著累加至第一個 case 12;由於沒有 break 語句,因此進入某個 case 後,其 case 下面的所有 case 都會被執行

  • 判斷該年份是否為閏年標準:
    • 可以被4整除,但不可以被100整除
    • 可以被400整除
public static void main(String[] args) {

    System.out.println("請輸入年份 : ");
    Scanner scanner = new Scanner(System.in);
    int year = scanner.nextInt();

    System.out.println("請輸入月份 : ");
    int month = scanner.nextInt();

    System.out.println("請輸入日期 : ");
    int date = scanner.nextInt();

    int result = 0;
    switch (month) {
        case 12:
            result += 30;
        case 11:
            result += 31;
        case 10:
            result += 30;
        case 9:
            result += 31;
        case 8:
            result += 31;
        case 7:
            result += 30;
        case 6:
            result += 31;
        case 5:
            result += 30;
        case 4:
            result += 31;
        case 3:
            // 判斷是否為閏年: true:29天 false:28天
            int daysOfFeb = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;

            result += daysOfFeb;
        case 2:
            result += 31;
        case 1:
            result += date;
    }
    System.out.println(month+"月"+date+"日為"+year+"年的第"+result+"天");
}
  • 輸出結果:
請輸入年份 : 
2008
請輸入月份 : 
3
請輸入日期 : 
17
3月17日為2008的第77天