2301_77356760 2023-04-21 18:02 采纳率: 33.3%
浏览 23

用java语言的for循环

用java中的for循环,做以下例题:输入某年某月某日,判断这一天是这一年的第几天?

  • 写回答

2条回答 默认 最新

  • Leodong. 2023-04-21 18:10
    关注

    这个网上找一下一大堆,通过baidu找了一个,可以跑的通的,具体如下:

    以下是Java代码实现:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入年份: ");
            int year = sc.nextInt();
            System.out.print("请输入月份: ");
            int month = sc.nextInt();
            System.out.print("请输入日期: ");
            int day = sc.nextInt();
            int sum = 0;
            int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
            // 判断是否为闰年
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                daysInMonth[1] = 29;
            }
            // 计算天数总和
            for (int i = 0; i < month - 1; i++) {
                sum += daysInMonth[i];
            }
            sum += day;
            // 输出结果
            System.out.println(year + "年" + month + "月" + day + "日是该年的第" + sum + "天。");
        }
    }
    

    运行结果示例:

    请输入年份: 2023
    请输入月份: 4
    请输入日期: 21
    2023年4月21日是该年的第111天。
    

    代码解释:

    1. 通过Scanner类获取用户输入的年、月、日。
    2. 定义一个名为daysInMonth的整型数组,数组中存储每个月的天数。
    3. 判断输入的年份是否为闰年,如果是则将数组中2月的天数设为29。
    4. 使用for循环计算输入日期在该年中是第几天,累加每个月的天数。
    5. 输出计算结果。

    如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

    评论

报告相同问题?

问题事件

  • 创建了问题 4月21日