这个小项目,新手可以拿来学习巩固循环和分支的相关语法,其中平闰年的判断是关键,
判断平闰年,对4取模等于0且对100取模不为0或者对400取模为0,就是闰年
package com.wb.practice;
import java.util.Scanner;
public class PrintCalendar {
/*
* 判断平闰年,对4取模等于0且对100取模不为0或者对400取模为0,就是闰年
*/
public static boolean isLeapYear(int year) {
boolean flag = false;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
flag = true;
} else {
return flag;
}
return flag;
}
/*
* 根据平闰年判断年份的总天数
*/
public static int yearDay(int year) {
int yearDay = 365;
if (isLeapYear(year)) {
yearDay = 366;
} else {
return yearDay;
}
return yearDay;
}
/*
* 根据输入的年份和月份判断这个月总共有多少天
*/
public static int monthDay(int year, int month) {
int monthDay = 31;
switch (month) {
case 1:
monthDay = 31;
break;
case 2:
if (isLeapYear(year)) {
monthDay = 29;
} else {
monthDay = 28;
}
break;
case 3:
monthDay = 31;
break;
case 4:
monthDay = 30;
break;
case 5:
monthDay = 31;
break;
case 6:
monthDay = 30;
break;
case 7:
monthDay = 31;
break;
case 8:
monthDay = 31;
break;
case 9:
monthDay = 30;
break;
case 10:
monthDay = 31;
break;
case 11:
monthDay = 30;
break;
case 12:
monthDay = 31;
break;
}
return monthDay;
}
public static int getTotalDay(int year, int month) {
int totalYearDay = 0;
int restMonthDay = 0;
for (int i = 1900; i <= year - 1; i++) {
totalYearDay += yearDay(i);
}
for (int i = 1; i < month; i++) {
restMonthDay += monthDay(year, i);
}
int totalDays = totalYearDay + restMonthDay;
return totalDays;
}
/*
* 计算每个月的第一天日历上所空的空格数
*/
public static int getSpace(int year, int month) {
return getTotalDay(year, month) % 7;
}
public static void printCalendar(int year, int month) {
int countDay = 0;//
System.out.println(year + "年 " + month + "月的日历如下");
System.out.println("==================================================");
System.out.println("一\t二\t三\t四\t五\t六\t日");
for (int i = 1; i <= getSpace(year, month); i++) {
System.out.print("\t");
countDay++;
}
for (int i = 1; i <= monthDay(year, month); i++) {
System.out.print(i + "\t");
countDay++;
if (countDay % 7 == 0) {
System.out.println();
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int year = sc.nextInt();
System.out.println("请输入月份");
int month = sc.nextInt();
System.out.println(isLeapYear(year) ? "是闰年" : "是平年");
System.out.println("整年有" + yearDay(year) + "天");
System.out.println(monthDay(year, month));
System.out.println(getTotalDay(year, month));
printCalendar(year, month);
System.out.println();
System.out.println("==================================================");
}
}