Java实现万年历
时间: 2023-11-13 14:16:17 浏览: 103
java实现万年历
好的,以下是Java实现万年历的代码:
```java
import java.util.Scanner;
public class Calendar {
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();
System.out.println("日\t一\t二\t三\t四\t五\t六");
//确定当前月的第一天是星期几
int firstDayOfWeek = getFirstDayOfWeek(year, month);
//确定当前月的天数
int totalDays = getTotalDaysOfMonth(year, month);
//打印日历
int day = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (i == 0 && j < firstDayOfWeek) {
System.out.print("\t");
} else if (day > totalDays) {
break;
} else {
System.out.print(day + "\t");
day++;
}
}
System.out.println();
}
}
//获取当前月的第一天是星期几
public static int getFirstDayOfWeek(int year, int month) {
int y = year;
int m = month;
if (m == 1 || m == 2) {
m += 12;
y--;
}
int d = 1;
int c = y / 100;
y = y % 100;
int w = (y + y / 4 + c / 4 - 2 * c + 26 * (m + 1) / 10 + d - 1) % 7;
if (w < 0) {
w += 7;
}
return w;
}
//获取当前月的天数
public static int getTotalDaysOfMonth(int year, int month) {
if (month == 2) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return 29;
} else {
return 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
}
```
运行后,会提示输入年份和月份,然后输出该月份的日历。
阅读全文