内容要求:
编写程序,实现如下功能:
提示用户输入一个年份和代表该年第一天是星期几的数字。说明星期日到星期六用0-6表示。
程序依次输出该年的每个月的日历。
运行实例:
输入年份: 2017
该年第1天是星期几: 0
分析:
题目的难点在于对每月第一天位置的处理,定义整型firstday来表示每月第一天的位置0<=firstday<=6,每个月的日期输出完后重新计算firstday,具体计算方法是firstday=(firstday+day)%7
代码片段如下:
import java.util.Scanner;
public class void calendar {
public static boolean leapyear(int year){//判断是否闰年
if((year%4==0&&year%100!=0)||year%400==0)return true;
else return false;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int year=0;//年份
year=sc.nextInt();//输入年份
int firstday=0;//每个月第一天
firstday=sc.nextInt();//输入第一月第一天
int day=0;//该月的天数
for(int mouth=1;mouth<=12;mouth++){
System.out.println(year+"年"+mouth+"月");
System.out.println("------------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
for(int i=firstday;i>0;i--)System.out.print(" ");
switch(mouth){//根据月份判断每月天数
case 1,3,5,7,8,10,12->{day=31;}
case 2->{if(leapyear(year))day=29;else day=28;}
case 4,6,9,11->{day=30;}
}
for(int j=1,k=firstday;j<=day;j++) {//j计数日期,k计数每周七天,输出天数
System.out.printf("%4d",j);
if (k == 6) {
System.out.println();
k = 0;
}
else k++;
}
firstday=(firstday+day)%7;//计算下月第一天
System.out.println();
System.out.println("------------------------------");
}
}
}