- 基础版
public static void main(String[] args) { System.out.println("请输入年份:"); Scanner input = new Scanner(System.in); int year = input.nextInt(); System.out.println("请输入月份:"); int month = input.nextInt(); //计算这个月有多少天 int days = 0; if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { days = 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { days = 30; } else { if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { days = 29; } else { days = 28; } } //2.算输入月份的1号是星期几 //2.1先算 你输进来的年份year年 距离 1900年相差的整年天数差 int sumYear = 0; for (int i = 1900; i < year; i++) { if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) { sumYear += 366; } else { sumYear += 365; } } //2.2再算year年的一月 距离month月的天数差 int sumMonth = 0; for (int i = 1; i < month; i++) { if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12) { sumMonth += 31; } else if (i == 4 || i == 6 || i == 9 || i == 11) { sumMonth += 30; } else { if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { sumMonth += 29; } else { sumMonth += 28; } } } //2.3计算year年month月1号是星期几? int week = (sumYear + sumMonth + 1) % 7; if (week == 0) { week = 7; } //3.打印日历 System.out.println(year + "年" + month + "月"); System.out.println("一\t二\t三\t四\t五\t六\t日"); for (int i = 1; i < week; i++) {//挤出前面 System.out.print("\t");//直接输出 } for (int i = 1; i <= days; i++) {//日历内容 System.out.print(i + "\t");//直接输出 if ((sumMonth + sumYear + i) % 7 == 0) {//换行 System.out.println();//输出后换行 } } }
最基础的写法,代码量大,但是思路最为清晰,新手必学!!!
- 进阶版
public static void main4(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入年份"); int year = input.nextInt(); System.out.println("请输入月份"); int month = input.nextInt(); Calendar calendar = Calendar.getInstance();//当前时间 calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); //这个月有多少天? int days = calendar.getActualMaximum(Calendar.DATE); //这个月的1号是星期几? calendar.set(Calendar.DATE, 1); int week = calendar.get(Calendar.DAY_OF_WEEK) == 1 ? 7 : calendar.get(Calendar.DAY_OF_WEEK) - 1; //calendar .get(Calendar.DAY_OF_WEEK) :获取1号是本周的第几天 //打印日历 System.out.println("一\t二\t三\t四\t五\t六\t日\t"); for (int i = 1; i < week; i++) { System.out.print("\t"); } for (int i = 1; i <= days; i++) { System.out.print(i + "\t"); calendar.set(Calendar.DATE, i); if (calendar.get(Calendar.DAY_OF_WEEK) == 1) { System.out.println(); } } }
采用日期时间类,使用Canlendar,代码更加简单,更加便捷。