java从键盘输入年份和月份, 输出该月份的日历表:
时间: 2024-06-08 14:05:57 浏览: 59
以下是一个基于控制台的 Java 代码示例,用于输入年份和月份,然后输出该月份的日历表:
```java
import java.util.Scanner;
public class PrintCalendar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 输入年份和月份
System.out.print("请输入年份: ");
int year = input.nextInt();
System.out.print("请输入月份: ");
int month = input.nextInt();
// 计算当月第一天是星期几
int firstDayOfWeek = getFirstDayOfWeek(year, month);
// 输出日历表头
System.out.printf("%10s%s\n", "", getMonthName(month) + " " + year);
System.out.println("-------------------------------------------------");
System.out.printf("%s%s%s%s%s%s%s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
// 输出日历表格
for (int i = 0; i < firstDayOfWeek; i++) {
System.out.printf("%4s", "");
}
for (int i = 1; i <= getNumDaysInMonth(year, month); i++) {
System.out.printf("%4d", i);
if ((i + firstDayOfWeek) % 7 == 0) {
System.out.println();
}
}
}
// 获取指定年份、月份的第一天是星期几(0 表示星期日,1 表示星期一,依次类推)
public static int getFirstDayOfWeek(int year, int month) {
int day = 1;
if (month < 3) {
month += 12;
year--;
}
int century = year / 100;
year %= 100;
int weekday = (day + 13 * (month + 1) / 5 + year + year / 4 + century / 4 + 5 * century) % 7;
return (weekday + 6) % 7;
}
// 获取指定月份的天数
public static int getNumDaysInMonth(int year, int month) {
int numDays = 0;
switch (month) {
case 1: numDays = 31; break;
case 2:
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
numDays = 29;
} else {
numDays = 28;
}
break;
case 3: numDays = 31; break;
case 4: numDays = 30; break;
case 5: numDays = 31; break;
case 6: numDays = 30; break;
case 7: numDays = 31; break;
case 8: numDays = 31; break;
case 9: numDays = 30; break;
case 10: numDays = 31; break;
case 11: numDays = 30; break;
case 12: numDays = 31; break;
default: break;
}
return numDays;
}
// 获取指定月份的名称
public static String getMonthName(int month) {
String monthName = "";
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December"; break;
default: break;
}
return monthName;
}
}
```
运行代码后,会提示输入年份和月份,然后输出该月份的日历表。例如,输入 2022 和 9,会输出如下的日历表:
```
September 2022
-------------------------------------------------
SunMonTueWedThuFriSat
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
```
阅读全文