思路
通過在一個數組中確定每個月份的天數,通過鍵盤獲取到年份及月份,先判斷輸入是否合法,輸入非法的話輸出提示,然后判斷是否為閏年,如果輸入的年份是閏年,則該月的2月份有29天,否則進入數組取得該月份對應的值作為天數返回並輸出。
代碼
import java.util.Scanner;
public class getDate {
//定義一個月份天數數組
static int[] arr = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
System.out.println("輸入年份及月份獲取該月天數,年份及月份用空格隔開:");
int year = scan.nextInt();
int month = scan.nextInt();
int i;
if(check_vaild(year,month)==-1){
System.out.println("輸入錯誤");
}else{
System.out.println(check_vaild(year,month));
}
}
public static int check_vaild(int year, int month) {
if (month == 0 || month > 12) {
return -1;
}
if (month != 2) {
return arr[month]; //返回數組中每個月的天數
} else { //判斷閏年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return 29;
} else {
return 28;
}
}
}
}