java编写 随机输入年月,要求显示这个月的天数。
时间: 2024-10-01 15:02:09 浏览: 55
在Java中,你可以使用`java.time`包下的`MonthDay`类来获取指定月份的天数。首先,你需要让用户输入年份和月份,然后创建一个`MonthDay`实例,最后获取并打印出该月份的总天数。以下是一个简单的示例:
```java
import java.time.Month;
import java.time.MonthDay;
public class MonthDaysCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份(1-12):");
int month = scanner.nextInt();
// 检查输入是否合法
if (month < 1 || month > 12) {
System.out.println("月份无效,请输入1到12之间的数字。");
return;
}
MonthMonthDay monthDay = MonthDay.of(year, month);
int daysInMonth = monthDay.lengthOfMonth(); // 获取该月天数
System.out.printf("年份 %d 的 %d 月有 %d 天。\n", year, month, daysInMonth);
}
}
```
在这个示例中,我们首先读取用户的输入,然后创建`MonthDay.of()`方法的实例,它会返回对应年份和月份的月日组合。`lengthOfMonth()`方法用于获取该月的实际天数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)