java日历软件设计
时间: 2023-12-20 15:32:31 浏览: 151
java设计日历
以下是一个简单的Java日历软件设计的示例:
```java
import java.util.Scanner;
public class CalendarSoftware {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入年份和月份
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
// 检查年份和月份的有效性
if (year < 1900 || month < 1 || month > 12) {
System.out.println("输入的年份或月份无效!");
return;
}
// 调用日历生成方法
generateCalendar(year, month);
}
public static void generateCalendar(int year, int month) {
// 输出日历标题
System.out.println("日\t一\t二\t三\t四\t五\t六");
// 计算该月第一天是星期几
int firstDayOfWeek = getFirstDayOfWeek(year, month);
// 计算该月的天数
int daysInMonth = getDaysInMonth(year, month);
// 输出日历内容
for (int i = 0; i < firstDayOfWeek; i++) {
System.out.print("\t");
}
for (int i = 1; i <= daysInMonth; i++) {
System.out.print(i + "\t");
if ((firstDayOfWeek + i) % 7 == 0) {
System.out.println();
}
}
}
public static int getFirstDayOfWeek(int year, int month) {
// 根据公式计算星期几
int q = 1;
int m = month;
int K = year % 100;
int J = year / 100;
int h = (q + 13 * (m + 1) / 5 + K + K / 4 + J / 4 + 5 * J) % 7;
int dayOfWeek = (h + 5) % 7;
// 转换为星期天为第一天的格式
return (dayOfWeek + 6) % 7;
}
public static int getDaysInMonth(int year, int month) {
// 判断是否为闰年
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// 根据月份返回天数
switch (month) {
case 2:
return isLeapYear ? 29 : 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
}
```
阅读全文