/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static Scanner sc=new Scanner(System.in);
static int year;
static int month;
public static void main(String[] args){
System.out.println("请输入年份:");
String ye=sc.next();
while(true){
if(ye.matches("\\d{4}")){
year=Integer.parseInt(ye);
break;
}else{
System.out.println("年份输入错误,请重新输入");
}
}
System.out.println("请输入月份:");
String mon=sc.next();
while(true){
if(mon.matches("[1-9]|0[1-9]|1[012]")){
month=Integer.parseInt(mon);
break;
}else{
System.out.println("月份输入错误,请重新输入");
}
}
Calendar cal=Calendar.getInstance();
cal.set(year, month-1, 1);
int day=cal.getActualMaximum(Calendar.DATE);
int index=cal.get(Calendar.DAY_OF_WEEK); //判断该月第一天是星期几,输出几个空格
System.out.println("日"+"\t"+"一"+"\t"+"二"+"\t"+"三"+"\t"+"四"+"\t"+"五"+"\t"+"六"+"\t");
for(int i=0;i<index-1;i++){
System.out.print(" "+"\t");
}
for(int i=1;i<=day;i++){ //输出该月每天,输出七个换行
System.out.print(i+"\t");
if((index-1+i)%7==0){
System.out.println("");
}
}
}
}
输入
2018
5
输出
日 一 二 三 四 五 六
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
https://ideone.com/pWF1sR
在线上机测试通过