Java中可以使用java.util.Calendar和java.text.SimpleDateFormat类来实现万年历上一月、下一月、上一年、下一年的查询。
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();
int[][] months = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
int days = months[isLeapYear(year)][month - 1];
String[] weeks = {"日", "一", "二", "三", "四", "五", "六"};
int weekIndex = getWeekIndex(year, month, 1);
int lastMonthDays = getLastMonthDays(year, month);
printCalendar(year, month, days, weeks, weekIndex, lastMonthDays);
while (true) {
System.out.print("请输入要查询的年份(上一年:preYear 下一年:nextYear):");
String input = scanner.next();
if ("preYear".equals(input)) {
if (month == 1) {
year--;
month = 12;
} else {
month--;
}
} else if ("nextYear".equals(input)) {
if (month == 12) {
year++;
month = 1;
} else {
month++;
}
} else {
year = Integer.parseInt(input);
}
printCalendar(year, month, days, weeks, weekIndex, lastMonthDays);
}
}
//打印日历
public static void printCalendar(int year, int month, int days, String[] weeks, int weekIndex, int lastMonthDays) {
System.out.println(year + "年" + month + "月");
System.out.println("日\t一\t二\t三\t四\t五\t六");
//打印上月的空格
for (int i = 1; i < weekIndex; i++) {
System.out.print("\t");
}
//打印上月的日期
for (int i = lastMonthDays - weekIndex + 1; i <= lastMonthDays; i++) {
System.out.print(i + "\t");
}
//打印当前月的日期
for (int i = 1; i <= days; i++) {
System.out.print(i + "\t");
weekIndex++;
if (weekIndex % 7 == 0) {
System.out.println();
}
}
//打印下月空格
for (int i = 1; i <= 42 - weekIndex - lastMonthDays; i++) {
System.out.print("\t");
}
System.out.println();
}
}