方法一:
import java.util.Calendar;
import java.util.Scanner;
public class YueLi {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();//a表示你将要输入几个年月
sc.nextLine();
Calendar calendar = Calendar.getInstance();
for(int i = 0; i < a; i++){
String s = sc.nextLine();
String[] strs = s.split("-");
int year = Integer.parseInt(strs[0]);
int month = Integer.parseInt(strs[1]);
calendar.set(Calendar.YEAR, year); //设置年
calendar.set(Calendar.MONTH, month-1);
calendar.set(Calendar.DATE, 1);
//System.out.println(calendar.get(7));
for(int j =1; j < calendar.get(Calendar.DAY_OF_WEEK); j++) {
System.out.print(" ");//输出开始前面的空格
}
for(int k = 1; k <= whichMonth(year, month); k++) {
calendar.set(Calendar.DATE, k);
if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println();
if(k <= 10) { //为了输出对齐
System.out.print(k+" ");
} else {
System.out.print(k+ " ");
}
}
}
}
public static int whichMonth(int year, int month) {
int days = 0;
switch (month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {//润年
days = 29;
} else {
days = 28;
}
break;
}
return days;
}
}
方法二:
import java.util.Scanner;
public class DisplayYueLi{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String input1=sc.nextLine();
String[] input2=input1.split("-");
int year=Integer.parseInt(input2[0]);
int month=Integer.parseInt(input2[1]);
int fristDay=GetfristDay(year,month);//
int mDay=GetmDay(year,month);
DisplayYueLi(fristDay,mDay);
}
static int GetfristDay(int year,int month){
int zDays=0;
for(int i=1;i<year;i++){
if(i%4==0&&i%100!=0||i%400==0){
zDays=zDays+366;
}
else{
zDays=zDays+365;
}
}
for(int j=1;j<month;j++){
switch(j){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
zDays=zDays+31;
break;
case 4:
case 6:
case 9:
case 11:
zDays=zDays+30;
break;
case 2:
if(year%4==0&&year%100!=0||year%400==0){
zDays=zDays+29;
}
else{
zDays=zDays+28;
}
}
}
int fristDay=(int)(zDays+1)%7;
// System.out.println("fristDay=" +fristDay);
return(fristDay);
}
static int GetmDay(int year,int month){
int mDay=0;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
mDay=31;
break;
case 4:
case 6:
case 9:
case 11:
mDay=30;
break;
case 2:
if(year%4==0&&year%100!=0||year%400==0){
mDay=29;
}
else{
mDay=28;
}break;
}
return(mDay);
}
static void DisplayYueLi(int fristDay,int mDay){
String space=" ";
System.out.println(space+"日"+space+"一"+space+"二"+space+"三"+space+"四"+space+"五"+space+"六");
for(int m=0;m<fristDay;m++){
System.out.print(space+" ");
}
for(int n=1;n<=mDay;n++){
if((n+fristDay)%7==0&&n!=1){
if (n<10)
System.out.println(space+" "+n);
else
System.out.println(space+n);
}
else{
if (n<10)
System.out.print(space+" "+n);
else
System.out.print(space+n);
}
}
}
}