从键盘输入一个年份和一个月份,输出月份有多少天,把判断条件放在一个类里面,java
时间: 2023-05-21 07:05:34 浏览: 89
当然可以,请看下面的代码:
```
public class MonthDayCounter {
public static int countDays(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 ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("Invalid month!");
break;
}
return days;
}
}
```
您可以将上面的类保存到一个名为"MonthDayCounter.java"的文件中,然后在另一个 Java 文件中创建一个对象并调用 countDays 方法来得到相应的结果。
比如:
```
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input the year: ");
int year = scanner.nextInt();
System.out.print("Input the month: ");
int month = scanner.nextInt();
int days = MonthDayCounter.countDays(year, month);
System.out.println("The number of days in the given month is " + days);
}
}
```
当您运行上面的程序并输入一个年份和一个月份时,它会输出该月份所包含的天数。
阅读全文