资源描述
输出任意一年的日历
import java.util.Scanner;
public class SwitchCycle_03
{
static int year,weekDay; //定义静态变量,以便其他类调用
public static boolean isLeapYear(int year) //判断是否为闰年
{
return ((year%4==0&&year%100!=0)||year%400==0);
}
//计算每年的第一天是星期几
public static int firstWeekDayOfYear(int year)
{
long day=365*(year-1); //从(公元1年的第一天是星期一)开始至今的大致天数
for(int i=1;i<year;i++) //year年的第一天,所以只计算前year年的总天数
{
if(isLeapYear(i))
day++; //计算总天数
}
return ((int)day%7)+1;
}
//计算每个月的天数
public static int getMonthOfDays(int month)
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if(isLeapYear(year))
return 29;
else
return 28;
default:
return 0;
}
}
//日历输出
public static void showMonths()
{
for(int m=1;m<=12;m++) //逐一打印出月份
{
System.out.println(m+"月");
System.out.println("Sunday Monday Tuesday Wednesday Thursday Friday Saturday ");
for(int j=1;j<=weekDay;j++)
{
System.out.print(" "); //10格作为开头的间隔
}
int monthDay=getMonthOfDays(m); //获取每个月的天数
for(int d=1;d<=monthDay;d++)
{
if(d<10)
System.out.print(" 0"+d+" ");
else
System.out.print(" "+d+" ");
weekDay=(weekDay+1)%7; //判断当天第二天是星期几(输出一天,星期加1)
if(weekDay==0) //星期天
System.out.println(); //每个星期换行
}
System.out.println(); //每个月换行
print();
}
print();
}
public static void print()
{
System.out.println("********************************************************************");
}
public static void main(String[] args)
{
System.out.println("请输入一个年份(公元1年及以后):");
loop:while(true)
{
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
year=Integer.parseInt(str);
if(year>=1)
{
break loop;
}
System.out.println("请输入正确的年份:");
}
weekDay=firstWeekDayOfYear(year);
print();
System.out.println("\t\t\t 公元 "+year+" 年 ");
print();
showMonths();
}
}
展开阅读全文