java根据给定的年、月输出该月的天数用Scaner写输入
时间: 2024-10-12 15:16:37 浏览: 26
在Java中,你可以使用`java.time`包下的`MonthDay`类以及`Scanner`类来获取用户输入的年份和月份,并计算出该月的天数。以下是步骤:
首先,需要导入必要的日期时间API:
```java
import java.time.Month;
import java.time.MonthDay;
import java.util.Scanner;
```
然后,创建一个`Scanner`对象来获取用户的输入:
```java
Scanner scanner = new Scanner(System.in);
```
接下来,询问用户输入年份和月份:
```java
System.out.print("请输入年份: ");
int year = scanner.nextInt();
System.out.print("请输入月份(1-12): ");
int month = scanner.nextInt() - 1; // 因为MonthDay的月份从0开始计数
```
计算并输出该月的天数:
```java
MonthDay monthDay = MonthDay.of(year, month);
int daysInMonth = monthDay.lengthOfMonth(); // 获取指定月份的天数
System.out.printf("'%d-%d'年的%tm月有%d天.", year, month + 1, month + 1, daysInMonth);
```
最后,别忘了关闭`Scanner`对象:
```java
scanner.close();
```
完整代码示例:
```java
import java.time.Month;
import java.time.MonthDay;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份: ");
int year = scanner.nextInt();
System.out.print("请输入月份(1-12): ");
int month = scanner.nextInt() - 1;
MonthDay monthDay = MonthDay.of(year, month);
int daysInMonth = monthDay.lengthOfMonth();
System.out.printf("'%d-%d'年的%tm月有%d天.", year, month + 1, month + 1, daysInMonth);
scanner.close();
}
}
```
阅读全文