package API;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;
public class PrintCalendar {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 二维数组 + 获取星期当作数组索引 +
// 年
System.out.println("请输入年份");
Scanner y = new Scanner(System.in);
int yearInput = y.nextInt();
// 月
System.out.println("请输入月份");
Scanner m = new Scanner(System.in);
// calendar是从0开始的,所以要减一
int monthInput = m.nextInt() - 1;
// 实例化对象
PrintTitle p = new PrintTitle();
// 输出标题日期
System.out.println(p.getDateTitle(yearInput, monthInput));
// 输出日历
System.out.println("日 \t一 \t二\t 三\t 四 \t五\t 六");
int[][] arr = new int[7][5];
int index = p.getDateWeek(yearInput, monthInput);
int sum = 0, flag = 0;
String t = " ";
// arr[i].length 5 arr.length 7
for (int i = 0; i < arr[i].length; i++) {
if (flag == 0) {
for (int j = 0; j < index; j++) {
System.out.print("");
System.out.print("\t");
}
for (int j = index; j < arr.length; j++) {
sum += 1;
System.out.print(sum + "\t");
}
flag++;
System.out.println();
} else {
for (int j = 0; j < arr.length && sum < p.getDaysOfMonth(yearInput, monthInput); j++) {
sum += 1;
System.out.print(sum + "\t");
}
System.out.println();
}
}
}
}
class PrintTitle {
public void getDateTitle() {
}
public String getDateTitle(int yearInput, int monthInput) {
// 创建SimpleDateFormat对象
SimpleDateFormat s1 = new SimpleDateFormat("\t" + "YYYY年MM月");
// 创建日历对象,通過輸入制定時間
Calendar c1 = Calendar.getInstance();
c1.set(yearInput, monthInput, 1, 9, 9, 9);
return s1.format(c1.getTime());
}
public int getDateWeek(int yearInput, int monthInput) {
// 根据日期取得星期几
SimpleDateFormat s2 = new SimpleDateFormat("EEEE");
// 创建日历对象,通過輸入制定時間
Calendar c2 = Calendar.getInstance();
c2.set(yearInput, monthInput, 1, 9, 9, 9);
String week = s2.format(c2.getTime());
String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
int week_index = 0;
;
for (int i = 0; i < weeks.length; i++) {
if (week.equals(weeks[i])) {
week_index = i;
break;
}
}
return week_index;
}
public int getDaysOfMonth(int yearInput, int monthInput) {
Calendar c3 = Calendar.getInstance();
c3.set(yearInput, monthInput, 1, 9, 9, 9);
return c3.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
测试结果: