判斷閏年平年,並輸出某月天數
題目
給定一個年份,判斷是閏年還是平年,再給定一個月份,輸出該月的天數。
分析
閏年的判斷條件是:
- 能被4整除但不被100整除
- 能被400整除
代碼
package practice;
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入年份:");
int year = scanner.nextInt();
if(isLeapYear(year)){
System.out.println("該年為閏年");
}else{
System.out.println("該年為平年");
}
System.out.println("請輸入月份:");
int month = scanner.nextInt();
int days;
while(month>12||month<1){
System.out.println("月份輸入有誤,請重新輸入");
}
switch (month){
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;
}
default:{
if(isLeapYear(year)){
days = 29;
}else{
days = 28;
}
}
}
System.out.println("該月有"+days+"天");
}
public static boolean isLeapYear(int y){
if(y%4==0&&y%100!=0||y%400==0){
return true;
}else{
return false;
}
}
}