用java写代码 输入某年某月某日判断这一天是这一年的第几天
以下是用Java编写的代码,可以输入某年某月某日,判断这一天是这一年的第几天:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
int year = input.nextInt();
System.out.print("请输入月份:");
int month = input.nextInt();
System.out.print("请输入日期:");
int day = input.nextInt();
int[] daysOfMonth = {31,28,31,30,31,30,31,31,30,31,30,31}; // 每个月份的天数
int days = 0; // 记录天数
// 判断是否为闰年
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
if (isLeapYear) {
daysOfMonth[1] = 29; // 闰年2月份有29天
}
// 累加当前月份之前的天数
for (int i = 0; i < month-1; i++) {
days += daysOfMonth[i];
}
// 累加当月的天数
days += day;
System.out.println(year + "年" + month + "月" + day + "日是这一年的第" + days + "天。");
}
}
运行结果:
请输入年份:2021
请输入月份:5
请输入日期:16
2021年5月16日是这一年的第136天。
``
原文地址: https://www.cveoy.top/t/topic/hkdn 著作权归作者所有。请勿转载和采集!