代码:
package com.sebase;
/*
* 万年历:
* 显示某一年某一月的日历
* 显示今年生肖是什么
* (以1990年为基准,马年, 1990.01.01是星期一)
* 马、羊、猴、鸡、狗、猪、鼠、牛、虎、兔、龙、蛇
* 显示是闰年还是平年
* 星期日 星期一 星期二 星期三 星期四 星期五 星期六
* 1 2 3 4 5 6
* ...
* ...
* 28 29 30
*
*/
import java.util.Scanner;
public class CalendarTest {
//计算年份的总天数
public static int countTotalDays(int year, int month){
int totalDays = 0;
for(int i=1990; i<year; i++){
if(isLeapyear(i)){
totalDays += 366;
}else{
totalDays += 365;
}
}
for(int i=1; i<month; i++){
totalDays += monthDays(year, i);
}
return totalDays;
}
//判断该年份是闰年还是平年
public static boolean isLeapyear(int year){
return (year%4==0 && year%100!=0 || year%400==0);
}
//计算当前月的天数
public static int monthDays(int year, int month){
int[] monthDay = {29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(month == 2 && isLeapyear(year)){
return monthDay[0];
}
return monthDay[month];
}
//计算该年对应的生肖
public static String countZodiac(int year){
String[] Zodiac = {
"马", "羊", "猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇" };
//0 1 2 3 4 5 6 7 8 9 10 11
return Zodiac[(year-1990)%12];
}
public static void printCalendar(int year, int month){
System.out.println(year + "年" + month+ "月的日历为:");
System.out.println(
"--------"+countZodiac(year)+"年"+"--------"+(isLeapyear(year) ? "闰年":"平年"));
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t");
//计算当前月的第一天是星期几
int totalDays = countTotalDays(year, month);
int firstDay = totalDays%7 + 1;
//因为显示星期日是第一列 所以不用加空格
if(firstDay == 7){
firstDay = 0;
}
for(int i=0; i<firstDay; i++){
System.out.print(" \t");
}
for(int i=1; i<=monthDays(year, month); i++){
System.out.print(i + " \t");
if((i+firstDay)%7 == 0){
System.out.println();
}
}
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("请输入要查询的年份:");
int year = scan.nextInt();
System.out.println("请输入要查询的月份");
int month = scan.nextInt();
printCalendar(year, month);
System.out.println("1为继续,0为退出,是否退出?");
int flag = scan.nextInt();
if(flag == 0){
break;
}
}
}
}