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月的天數,循環累加天數
