呀!忙碌的每一天,都忘记了明天就是我们愉快周末了。今天没有朋友的闲聊的话,明天处在绷紧的状态呢!还有朋友提到,所有今天来跟大家分享一下用java来编写日历表,累了想休息了的时候,打开看看,还有几天到周末!那么我们来看一下代码,具体怎么实现吧!
public class Demo6 {
public static void main(String[] args) {
Demo6 demo = new Demo6();
demo.show(2016,11); //输入年和月份
}
//定义一个方法:判断是平年还是闰年
public boolean isLeapYear(int year) {
if (year%400==0 || (year%4==0 && year%100 !=0)) {
return true;
}
return false;
}
//计算输入年份,月份的总天数
public int getTotalDateFrom(int year, int month) {
int totalDate = 0;
for (int i = 1900; i < year; i++) {
//判断是闰年还是平年
if (isLeapYear(year)) {
totalDate += 366;
}else{
totalDate += 365;
}
}
//计算2月份的天数
for (int i = 1; i < month; i++) {
totalDate += getDayOfMonth(year, month);
}
return totalDate;
}
//返回一个天数
public int getDayOfMonth(int year,int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
default:
return 30;
}
}
public int printSpace(int year, int month){
return getTotalDateFrom(year, month)%7;
}
public void print(int year, int month){
int countSpac = printSpace(year, month)+1; //空格的个数
int coun = 0; //定义一个计数
for (int i = 0; i < countSpac; i++) {
coun ++;
System.out.print("\t");
}
//打印日期
for (int i = 0; i < getDayOfMonth(year, month); i++) {
if (coun % 7 == 0) {
System.out.println();
}
coun++;
System.out.print(i+"\t");
}
}
public void show(int year, int month){
System.out.println(" **************"+year+"******"+month+"***************");
System.out.println("=======================================================");
System.out.println("日\t一\t二\t三\t四\t五\t六");
System.out.println("=======================================================");
print(year, month);
System.out.println();
}
}
实现效果如下: