
解析:
这题主要考虑的两个点分别是
- 每个月份天数的判断,除了2月份,其他月份分为大月和小月,大月31天,小月30天
- 当前年份是闰年或者平年的判断,平年2月份28天,闰年2月份29天
我封装了两个方法,一个方法reDay()是输入当前月份和年份,会返回当前月份的天数;另一个方法reYear()是输入当前年份,会返回当前年份是闰年或者平年。
判断月份天数的方法
// 返回当前月份有多少天数的方法
public static int reDay(int num, int year) {
int days = 0;
switch (num) {
// 二月份天数,区分闰年和平年
case 2:
if (reYear(year)) {
days = 29;
} else {
days = 28;
}
break;
// 大月天数
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
// 小月天数
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
}
return days;
}
判断年份的方法
// 返回当前月份有多少天数的方法
public static int reDay(int num, int year) {
int days = 0;
switch (num) {
// 二月份天数,区分闰年和平年
case 2:
if (reYear(year)) {
days = 29;
} else {
days = 28;
}
break;
// 大月天数
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
// 小月天数
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
}
return days;
}
主体的实现代码很短
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
int month = scanner.nextInt();
int day = scanner.nextInt();
int result=0;
// 当前月份之前的月份天数相加
for(int i=1;i<month;i++) {
result+=reDay(i, year);
}
// 加上当前的日期是几号就是最终的天数了
result+=day;
System.out.println(result);
}
全部代码预览
package _3_5_test;
import java.util.Scanner;
/*天数计算
* 1、定义一个方法,用于对平年和闰年的判断
* 2、闰年的2月份是29天
* 3、 1、3、5、7、8、10、12月份是31天 4、6、9、11是30天
*
* */
public class SixTwo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
int month = scanner.nextInt();
int day = scanner.nextInt();
int result=0;
// 当前月份之前的月份天数相加
for(int i=1;i<month;i++) {
result+=reDay(i, year);
}
// 加上当前的日期是几号就是最终的天数了
result+=day;
System.out.println(result);
}
// 返回当前月份有多少天数的方法
public static int reDay(int num, int year) {
int days = 0;
switch (num) {
// 二月份天数,区分闰年和平年
case 2:
if (reYear(year)) {
days = 29;
} else {
days = 28;
}
break;
// 大月天数
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
// 小月天数
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
}
return days;
}
// 判断平年和闰年的方法,如果是闰年返回true;
public static boolean reYear(int num) {
boolean flag = false;
if ((num % 4 == 0 && num % 100 != 0) || num % 400 == 0) {
flag = true;
}
return flag;
}
}
效果展示
