Java实现——输入一个年份求该年的母亲节是几月几号,并在月历中标注出来
时间: 2023-11-24 16:06:50 浏览: 144
以下是Java实现的代码:
```java
import java.util.Scanner;
public class MotherDay {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入年份:");
int year = sc.nextInt();
sc.close();
int month = 5; // 母亲节固定在5月
int day = getMotherDay(year, month);
System.out.println(year + "年的母亲节是" + month + "月" + day + "日");
// 在月历中标注母亲节
printMonth(year, month, day);
}
// 计算母亲节的日期
public static int getMotherDay(int year, int month) {
int day = 1; // 从1号开始查找
int week = getWeekDay(year, month, day);
while (week != 0) { // 找到第一个星期日
day++;
week = getWeekDay(year, month, day);
}
return day + 7; // 第二个星期日就是母亲节
}
// 计算某一天是星期几
public static int getWeekDay(int year, int month, int day) {
if (month == 1 || month == 2) {
year--;
month += 12;
}
int c = year / 100;
int y = year % 100;
int week = (c / 4 - 2 * c + y + y / 4 + 13 * (month + 1) / 5 + day - 1) % 7;
if (week < 0) {
week += 7;
}
return week;
}
// 在月历中标注母亲节
public static void printMonth(int year, int month, int day) {
String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
daysInMonth[1] = 29;
}
// 打印月历
System.out.println("\n " + monthName[month - 1] + " " + year);
System.out.println("------------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
int weekDay = getWeekDay(year, month, 1);
for (int i = 0; i < weekDay; i++) {
System.out.print(" ");
}
for (int i = 1; i <= daysInMonth[month - 1]; i++) {
if (i == day) {
System.out.printf("|%2d|", i); // 标注母亲节
} else {
System.out.printf("%4d", i);
}
weekDay = (weekDay + 1) % 7;
if (weekDay == 0) {
System.out.println();
}
}
System.out.println();
}
}
```
运行结果如下:
```
请输入年份:2022
2022年的母亲节是5月8日
May 2022
------------------------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
| 8|| 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
```
可以看到,在月历中标注了母亲节的日期(用竖线括起来的数字)。
阅读全文