用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天。代码解释:
- 通过
Scanner类获取用户输入的年、月、日。 - 定义一个名为
daysInMonth的整型数组,数组中存储每个月的天数。 - 判断输入的年份是否为闰年,如果是则将数组中2月的天数设为29。
- 使用
for循环计算输入日期在该年中是第几天,累加每个月的天数。 - 输出计算结果。
如果以上回答对您有所帮助,点击一下采纳该答案~谢谢
评论 打赏 举报解决 1无用- 通过