总评A+,答案仅供参考
写出解决如下问题的程序代码,并在代码中用注释说明满足了如下4个基本的设计要求
问题:输入两个整数年月,如果年月有效则返回该年月天数,否则返回-1要求:
- 单模块单功能
- 命名风格一致
- 名称可读性好
- 风格布局一致
// yearAndMonth2Days.java
package 作业6;
// 命名风格一致:驼峰命名法
// 名称可读性好
public class yearAndMonth2Days {
private int year;
private int month;
public yearAndMonth2Days(int year, int month) {
this.year = year;
this.month = month;
}
public int getDays() {
int[] daysOfMonthArray = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 判断是否为2月
if (this.month != 2) {
return daysOfMonthArray[this.month - 1];
} else {
int daysInFeb = daysOfMonthArray[this.month - 1];
if (isLeapYear(year)) {
return daysInFeb + 1; // 闰年29天
} else {
return daysInFeb; // 非闰年28天
}
}
}
// 判断某年是否为闰年是否,单模块单功能
private boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
}
// Demo.java
package 作业6;
import java.util.Scanner;
// 风格布局一致
public class Demo {
private static final String regEx = "^(\d{4})\s+((0?[1-9])|(1[0|1|2]))$";
private static boolean checkInput(String input) {
return input.matches(regEx);
}
private static yearAndMonth2Days getYearAndMonth(String input) {
String[] arr = input.split(" ");
return new yearAndMonth2Days(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入年月,以空格隔开");
String input = in.nextLine();
if (checkInput(input)) {
yearAndMonth2Days obj = getYearAndMonth(input);
System.out.println(obj.getDays()); // 返回该年月天数
} else {
System.out.println(-1); // 错误
}
in.close();
}
}
运行结果
请输入年月,以空格隔开
2022 0
-1
进程已结束,退出代码0
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)