Java用do while改写根据年份月份输出该月天数的程序,使程序能够判断10个年份月份的天数
时间: 2024-06-15 21:06:04 浏览: 90
JS根据年月获得当月天数的实现代码
使用do-while循环可以实现根据年份月份输出该月天数的程序,并且可以判断10个年份月份的天数。以下是示例代码:
```java
import java.util.Scanner;
public class MonthDays {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = 1;
do {
System.out.println("请输入第" + count + "个年份:");
int year = scanner.nextInt();
System.out.println("请输入第" + count + "个月份:");
int month = scanner.nextInt();
int days = getMonthDays(year, month);
System.out.println(year + "年" + month + "月的天数为:" + days);
count++;
} while (count <= 10);
scanner.close();
}
public static int getMonthDays(int year, int month) {
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 (isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("输入的月份无效!");
}
return days;
}
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
```
阅读全文