首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 入門練習:輸入月份輸出天數(含閏年判斷)

     編輯:程式設計疑難解答

題目要求

用戶輸入 1-12 的整數代表月份,程序輸出該月天數。需考慮 2 月閏年情況。

核心邏輯

  1. 定義天數數組:int[] days = {31,28,31,30,31,30,31,31,30,31,30,31}; 索引 0 對應 1 月。
  2. 輸入校驗:月份範圍 1-12,否則提示錯誤。
  3. 閏年判斷:(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)。若為閏年且月份為 2,天數 +1。

完整代碼示例

import java.util.Scanner;

public class MonthDays {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("請輸入年份: ");
        int year = sc.nextInt();
        System.out.print("請輸入月份(1-12): ");
        int month = sc.nextInt();

        if (month < 1 || month > 12) {
            System.out.println("月份輸入錯誤!");
            return;
        }

        int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
        boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        if (leap && month == 2) days[1] = 29;

        System.out.printf("%d 年 %d 月 有 %d 天%n", year, month, days[month - 1]);
    }
}

進階思考

  • 使用 java.time.YearMonth (Java 8+) 一行搞定:YearMonth.of(year, month).lengthOfMonth()。
  • 異常處理:InputMismatchException 捕獲非數字輸入。

基礎語法練習,邏輯清晰是關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved