Java 输入月份判断该月天数(switch)
代码不一定是最好的,仅给予初学者思路
// 实例化Scanner
Scanner scan = new Scanner(System.in);
// 提示用户输出月份
System.out.println("请输入月份:");
// 接收用户输入的月份
int month = scan.nextInt();
// 判断月份(注意break位置)
switch (month) {
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:
System.out.println("请输入对应年份:");
int year = scan.nextInt();
// 闰年判断
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
System.out.println("29天");
} else {
System.out.println("28天");
}
break;
default:
System.out.println("请输入正确月份~");
break;
}
阅读更多