试题 算法提高 任意年月日历输出(Java)
试题 算法提高 任意年月日历输出(Java)
import java.util.Calendar;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
int month = sc.nextInt();
sc.close();
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
int week = cal.get(Calendar.DAY_OF_WEEK);//一号是星期几
System.out.println("Calendar " + year + "-" + (month >= 10 ? month : "0" + month));
System.out.println("---------------------");
System.out.println(" Su Mo Tu We Th Fr Sa");
System.out.println("---------------------");
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//这个月天数
//第一行日期
for (int i = 2 - week, j = 0; i <= days; ++i, ++j) {
if (j == (7 - week + 1)) {
break;
}
if (i <= 0) {
System.out.print(" ");
j--;
continue;
}
System.out.printf(" %2d", i);
}
//后面n行日期
for (int i = (7 - week + 1) + 1, j = 0; i <= days; ++i, ++j) {
if (j % 7 == 0) {
System.out.println();
}
System.out.printf(" %2d", i);
}
System.out.println();
System.out.println("---------------------");
}
}
试题 算法提高 任意年月日历输出(Java)相关教程