import java.util.Scanner;
//我的万年历
public class MyCalendar
{
public static void main(String[] args)
{
int year;//1900<=year<=2200
int month;//1<=month<=12
int icount = 0;
int monthdays=0;//当月天数
int week;//year年month月1号是星期几
System.out.println("欢迎使用本系统!");
int[] arr = Scan_in();
year = arr[0];
month = arr[1];
if(isRun(year))
{
System.out.println(year+"年是闰年");
}
else
{
System.out.println(year+"年是平年");
}
System.out.println("您要查询的是:"+year+"年"+month+"月1日,距离1900年1月1日已经过去了"+TotalDays(year, month)+"天\n");
System.out.println("星期天\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t");
week = TotalDays(year,month)%7;
monthdays = MonthDay(year,month);
for(int i=0;i<week;i++)
{
System.out.print("\t");
icount++;
}
for(int i=1;i<=monthdays;i++)
{
System.out.print(i+"\t");
icount++;
if(icount%7==0)
{
System.out.println();
}
}
}
//输入年份,显示当前年份是否闰年
public static boolean isRun(int year)
{
if((year%4==0&&year%100!=0)||(year%400==0))
{
return true;//返回真,是闰年
}
else
{
return false;//返回假,是平年
}
}
//输入年份,月份 计算出当月天数
public static int MonthDay(int year,int month)
{
int MonthDays;//当月天数
switch(month)
{
case 4:
case 6:
case 9:
case 11:
MonthDays = 30;
break;
case 2:
if(isRun(year))
{
MonthDays = 29;
}
else
{
MonthDays = 28;
}
break;
default:MonthDays = 31;
}
return MonthDays;
}
//计算从1900-1-1到当月1号共过了多少天
public static int TotalDays(int year,int month)
{
int TotalDays = 1;//计算从1900-1-1到今天总过过了多少天
for(int i=1900;i<year;i++)
{
if(isRun(i))
{
TotalDays += 366;
}
else
{
TotalDays += 365;
}
}
for(int i=1;i<month;i++)
{
TotalDays += MonthDay(year,i);
}
//System.out.println("从1900-1-1至"+year+"-"+month+"-"+"1共过去了"+TotalDays+"天!");
return TotalDays;
}
public static int[] Scan_in()
{
int[] arr = new int[2];//存储输入的年份与月份
boolean flag;
do
{
Scanner in = new Scanner(System.in);
System.out.print("请输入查询年份:");
arr[0] = in.nextInt();
System.out.print("请输入查询月份:");
arr[1] = in.nextInt();
if((1900<=arr[0]&&arr[0]<=2200)&&(1<=arr[1]&&arr[1]<=12))//判断年份与月份是否合法
{
flag = false;
}
else
{
System.out.println("输入的年份与月份不符合国情,请重新输入!");
flag = true;
}
}
while (flag);
return arr;
}
}
原文地址:http://yilesh.blog.51cto.com/3169139/1572802