需求
输入年份,月份,日,判断这一天是这一年的第几天?(闰年的2月份为29天,平年为28天)
代码
import java.util.*;
public class Test {
/**
* 能被4整除且不能被100整除或者能被400整除的年份为闰年
* @param args
* @author 孙琨
*/
public static void main(String[] args) {
System.out.println("请输入年,月,日");
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
int totalDay = 0;
for (int i = 1; i < month; i++) {
totalDay += getMonthDay(year, i);
System.out.println("前" + i + "月总天数为" + totalDay);
}
System.out.println("总天数为: " + (totalDay + day));
}
}
public static int getMonthDay(int year,int month){
boolean flag = isLeapYear(year);
if (month == 2) {
if(flag == true) {
return 29;
} else {
return 28;
}
} else if (month==4 || month==6 || month==9 || month==11) {
return 30;
} else {
return 31;
}
}
public static boolean isLeapYear(int year){
if ((year%4==0 && year%100!=0) || (year%400==0)) {
return true;
} else {
return false;
}
}
}