一个可以查询1900年之后的所有年份当月月历。
import java.util.Scanner;
public class Calendar {//输入年月输出当月日历public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("请输入年份");int year = input.nextInt();System.out.println("请输入月份:");int month = input.nextInt();int count=0;//这些年之间闰年的个数for (int i =1900; i <year; i++) {//闰年个数必须用循环做,因为规则不单单4年一闰,所以不能用除法if(((i%4==0)&&(i%100!=0)||i%400==0)){count++;}}int days=(year-1900)*365+count;switch (month) {case 12:days+=30;case 11:days+=31;case 10:days+=30;case 9:days+=31;case 8:days+=31;case 7:days+=30;case 6:days+=31;case 5:days+=30;case 4:days+=31;case 3:days+=28;case 2:days+=31;case 1:days+=0;default:break;}if((((year%4==0)&&(year%100!=0)||year%400==0))&month>2){//如果查询的是闰年且大于2月,则要补上一天days++;}int dayinweek=days%7;//计算每月1号是星期几System.out.println(year+"年"+month+"月:");System.out.println("星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日");int day=0; //存储要打印的天数if(month==2){if((year % 400 == 0)|| (year % 4 == 0 &year%100!=0)){//如果查询的是闰年的2月,则要打印29天day=29;}else {day=28;}}else if(month==4||month==6||month==9||month==11){day=30;}else{day=31;}//以下是根据dayinweek(即当月1号在星期里的位置参数即月头起始空格数)和该月天数来做个打印输出int print_count=1;//给月头的空格与当月天数的和做个计数,实现7个数据就换行输出for(int i=1;i<=day+dayinweek;i++){while(dayinweek>0){System.out.print(" \t");dayinweek--;print_count++;}System.out.print(i+"\t");if(print_count%7==0) {System.out.println();//输出时每隔七天换行}print_count++;}}
}
转载于:https://blog.51cto.com/cktmyh/1627081