接收用户输入的年份year和月份month,计算该年该月的天数并输出,
首先我们需要知道平年有365,闰年有366天
其次,能被4整除且不能被100整除则为闰年,若是世纪年(整百年)的话能被400整除的的为闰年。
反之就是平年。
代码如下:
//1.用Scanner类,先导包
import java.util.Scanner;
public class If_exercise{
public static void main(String[] args){
//创建实例
Scanner sc = new Scanner(System.in);
//使用功能
//用户输入年份和月份
System.out.println("您的输入的年份为?");
int year = sc.nextInt();
System.out.println("您的输入的月份为?");
int month = sc.nextInt();
int day = 0;
int days = 0;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
case 2:
if((year % 4 ==0) && (year % 100 != 0)||(year % 400 == 0)){
day = 29;
}else{
day = 28;
}
break;
}
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){//闰年的判断规则
days=366;
}else{
days=365;
}
System.out.println(year+"年有"+days+"天");
System.out.println(month+"月有"+day+"天");
}
}
运行结果:
欢迎大家补充留言!