用java实现判断某年某月的天数
时间: 2023-05-27 13:04:37 浏览: 155
以下是一个用Java实现判断某年某月天数的示例代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
int year = input.nextInt();
if (year <= 0) {
System.out.println("年份无效!");
return;
}
System.out.print("请输入月份(1~12):");
int month = input.nextInt();
if (month < 1 || month > 12) {
System.out.println("月份无效!");
return;
}
int days = 0;
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;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
}
System.out.println(year + "年" + month + "月有" + days + "天!");
}
}
```
该程序通过`Scanner`类读取用户输入,然后根据输入的年份和月份来确定天数。其中,`switch`语句用于判断每个月的天数,对于2月需要根据闰年情况调整天数。通过对年份进行不同的计算,可以判断是否为闰年。最后使用`System.out.println()`方法输出结果。
阅读全文
相关推荐


















