题目:编写一个某年第一天是星期几的查询器:程序输出:XXXX年一月一日是 星期X
提示:1900年一月一日是星期一
思路解析:
1, 先算出今年距离1900年之间共有多少天,在计算总天数的时候,分两种情况考虑,第一种是对年的考虑,分闰年和平年,第二种是对月份的判断,也要注意分闰月和非闰月哦!!
2, 在算出了距离1900年的总天数后,根据(totalDays+1)%7这个公式算星期。
3, 有两个小细节需要注意的是:@以星期几为次数来循环打印空格,如下面这张图:
Week=1;即通过for(int i=0;i<week;i++){}来判断空格,如图中星期日到星期一的空格!
@月天数的换行,每七天换一行。如下图:
代码实现:
packagecom.rshz.lesson4;
importjava.util.Scanner;
public class Calendar {
/**
* 编写一个某年第一天是星期几的查询器:
* 程序输出:XXXX年一月一日是 星期X
提示:1900年一月一日是星期一
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = newScanner(System.in);//调用Scanner对象
//输入年和月
System.out.println("请输入年和月");
int year=in.nextInt();
int month=in.nextInt();
//定义总天数和月以及星期
long totalDays=0;
long week=0;
long monthDay=0;
// 对年的处理
for(int i=1900;i<year&&i>=1900;i++)
{
if(i%4==0&&i%100!=0||i%400==0)
{
totalDays=totalDays+366;//闰年
}
else
{
totalDays=totalDays+365;//平年
}
}
// 对月的处理
for(int i=1;i<month;i++)
{
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)
{
totalDays=totalDays+31;
}
else if(i==4||i==6||i==9||i==11)
{
totalDays=totalDays+30;
}
else
{
if(year%4==0&&year%100!=0||year%400==0)
{
totalDays=totalDays+29;//闰月
}
else
{
totalDays=totalDays+28;//平月
}
}
}
System.out.println("总天数:"+totalDays);
week=(totalDays+1)%7;//根据总天数算星期几
System.out.println("当月第一天是星期:"+week);
System.out.println("年份 "+year+"月份 "+month);
System.out.println("*********************************************************************");
System.out.println("日"+"\t"+"一"+"\t"+"二"+"\t"+"三"+"\t"+"四"+"\t"+"五"+"\t"+"六");
// 打印星期的空格
for(int i=0;i<week;i++)//根据星期来打印空格
{
System.out.print("\t");
}
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
monthDay=31;
}
else if(month==4||month==6||month==9||month==11)
{
monthDay=30;
}
else
{
if(year%4==0&&year%100!=0||year%400==0)
{
monthDay=29;
}
else
{
monthDay=28;
}
}
for(int i=1;i<=monthDay;i++)//遍历月的天数
{
System.out.print(i+"\t");
if((i+week)%7==0)//判断星期
{
System.out.println();
}
}
System.out.println();
System.out.println("*************************************************");
}
}