利用switch case 语句
>// 计算一个月有多少天
// 年 月
int year = 2058;
int month = 2;
// 2月份 闰年 1 如果年份能被4整除,且不能被100整除
// 2 年份能被400整除
// 1,3,5,7,10,12
switch (month) {
// 每个case默认都有一个break,根据逻辑,break也可以去掉。
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("31天");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("30天");
break;
case 2:
{
// 如果一个条件包含多个语句,用()包裹起来。
if ((year%4==0 && year%100 != 0) || (year % 400 == 0) ) {
System.out.println("29");
} else {
System.out.println("28");
}
System.out.println("这个是计算2月份天数的case");
}
break;
default:
break;
}
}
}
利用if else语句
>// 判断月份天数
int year,month=0;
System.out.println("输入你要计算的年份:");
Scanner scan = new Scanner(System.in);
System.out.println("输入你要计算的月份:");
Scanner scan1 = new Scanner(System.in);
year=scan.nextInt();
month=scan1.nextInt();
System.out.println(month);
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
System.out.println(year+"年"+month+"月有31天");
}
else if(month==4||month==6||month==9||month==11)
{
System.out.println(year+"年"+month+"月有30天");
}
// 判断是否为闰年
else if((year%4==0&&year%100!=0)||year%400!=0)
{
System.out.println(year+"年"+month+"月有29天");
}
// 不是闰年
else
System.out.println(year+"年"+month+"月有28天");