java不用方法显示日历
时间: 2024-01-22 19:20:42 浏览: 28
以下是Java代码,可以在控制台中打印出指定月份的日历:
```
import java.util.Scanner;
public class CalendarPrinter {
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();
scanner.close();
// 计算当月第一天是星期几
int firstDayOfWeek = getFirstDayOfWeek(year, month);
// 计算当月的天数
int daysOfMonth = getDaysOfMonth(year, month);
// 打印日历头部
System.out.println("日\t一\t二\t三\t四\t五\t六");
// 打印日历内容
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 > daysOfMonth) {
break;
} else {
System.out.print(day + "\t");
day++;
}
}
System.out.println();
}
}
/**
* 计算指定月份的天数
*/
private static int getDaysOfMonth(int year, int month) {
if (month == 2) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
/**
* 判断指定年份是否是闰年
*/
private static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
/**
* 计算指定月份的第一天是星期几
*/
private static int getFirstDayOfWeek(int year, int month) {
int century = year / 100;
int yearInCentury = year % 100;
int dayOfWeek = (yearInCentury + yearInCentury / 4 + century / 4 - 2 * century + 26 * (month + 1) / 10) % 7;
return (dayOfWeek + 7) % 7;
}
}
```
你可以运行这段代码并输入年份和月份,即可在控制台中打印出指定月份的日历。