java从键盘输入年份和月份, 输出该月份的日历表:
时间: 2023-11-27 07:54:55 浏览: 130
以下是一个简单的 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();
printCalendar(year, month);
}
public static void printCalendar(int year, int month) {
int days = getDaysOfMonth(year, month);
int firstDayOfWeek = getFirstDayOfWeek(year, month);
System.out.println("日 一 二 三 四 五 六");
for (int i = 1; i <= days; i++) {
if (i == 1) {
for (int j = 0; j < firstDayOfWeek; j++) {
System.out.print(" ");
}
}
System.out.printf("%2d ", i);
if ((i + firstDayOfWeek) % 7 == 0) {
System.out.println();
}
}
}
public static int getDaysOfMonth(int year, int month) {
int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year)) {
return 29;
}
return daysOfMonth[month - 1];
}
public static int getFirstDayOfWeek(int year, int month) {
int dayOfWeek = 0;
for (int i = 1900; i < year; i++) {
dayOfWeek = (dayOfWeek + 365 + (isLeapYear(i) ? 1 : 0)) % 7;
}
for (int i = 1; i < month; i++) {
dayOfWeek = (dayOfWeek + getDaysOfMonth(year, i)) % 7;
}
return dayOfWeek;
}
public static boolean isLeapYear(int year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
}
```
运行上述代码后,会提示输入年份和月份,输入后即可输出该月份的日历表。
阅读全文