public static void main(String[] args) {
System.out.println("接收用户输入一个月份和一个日期,计算出是一年当中的第几天");
System.out.println("\t输入月份后,按下回车,在输入日期");
System.out.println("\n请输入4位年数字");
while (true) {
int x;
int day = 0;
int cal = 0;
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
boolean leapYear = isLeapYear(year);
System.out.println("请输入月份:");
int month = scanner.nextInt();
// 闰年2月29天
if (month == 2 && leapYear) {
System.out.println("请输入日期:");
day = scanner.nextInt();
while (day > 29 || day < 1) {
System.out.println("输入有误,重新输入日期:");
x = scanner.nextInt();
day = x;
}
}
// 平年2月28天
if (month == 2 && !leapYear) {
System.out.println("请输入日期:");
day = scanner.nextInt();
while (day > 28 || day < 1) {
System.out.println("输入有误,重新输入日期:");
x = scanner.nextInt();
day = x;
}
}
if (month % 2 != 0) {
System.out.println("请输入日期:");
day = scanner.nextInt();
while (day > 31 || day < 1) {
System.out.println("输入有误,重新输入日期:");
x = scanner.nextInt();
day = x;
}
}
if (month != 2 && month % 2 == 0) {
System.out.println("请输入日期:");
day = scanner.nextInt();
while (day > 30 || day < 1) {
System.out.println("输入有误,重新输入日期:");
x = scanner.nextInt();
day = x;
}
}
System.out.println("你输入的是:" + year + "年" + month + "月" + day + "日");
cal = getDays(year, month, day);
System.out.println(year + "年" + month + "月" + day + "日, 是" + year + "中第" + cal + "天");
}
}
/**
* 判断是否是闰年
* 能被4整除且不能被100整除,或者 能被400整除
* @param year
* @return
*/
public static boolean isLeapYear(int year) {
boolean leapYear = false;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
leapYear = true;
}
return leapYear;
}
/**
* 根据年,月,日,计算总天数
* @param year
* @param month
* @return
*/
public static int getDays(int year, int month, int day) {
int arr[] = {31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30};
boolean leapYear = isLeapYear(year);
if (leapYear) {
arr[1] = 29;
}
int sum = 0;
for (int i = 0; i < month -1; i++) {
sum += arr[i];
}
sum = sum + day;
return sum;
}
代码逻辑:
(1)判断输入的年份是否是闰年,判断标准:能被4整除且不能被100整除 或者 能被400整除
(2)月份检查,分为4中情况
a.闰年且为2月,此时2月有29天
b.平年且为2月,此时2月有28天
c.平年,能被2整除,此时月份有30天
d.平年,不能被2整除,此时月份有31天
(3)计算天数,初始化一个平年的月份天数数组,如果为闰年,则更改数组中2月的天数,循环累加天数