java:do-while语句改写根据年份月份输出该月天数的程序,使程序能够判断10个年份月份的天数。
时间: 2024-06-15 07:06:02 浏览: 171
Java中的do-while语句可以用来实现循环,根据年份和月份输出该月的天数。下面是一个示例程序:
```java
import java.util.Scanner;
public class DaysInMonth {
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 = getDaysInMonth(year, month);
System.out.println(year + "年" + month + "月有" + days + "天");
count++;
} while (count <= 10);
scanner.close();
}
public static int getDaysInMonth(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);
}
}
```
这个程序会提示用户输入10个年份和月份,然后根据输入的年份和月份计算该月的天数,并输出结果。程序中使用了一个`getDaysInMonth`方法来计算每个月的天数,还使用了一个`isLeapYear`方法来判断是否是闰年。
阅读全文