实验3:输出指定年份的日历
题目类别: 实验
关键字: Java基本语法 输入输出 算术运算 关系运算 选择语句 循环语句
内容要求:
编写程序,实现如下功能:
提示用户输入一个年份和代表该年第一天是星期几的数字。说明星期日到星期六用0-6表示。
程序依次输出该年的每个月的日历。
运行实例:
输入年份: 2017
该年第1天是星期几: 0
提交要求:包含源程序文件的JAR
package mainpackge;
import java.util.Scanner;
class CalendarDetail {
private int year;
private int firstDay;
boolean isLeap;
public int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
CalendarDetail() {
year = 0;
firstDay = 0;
isLeap = false;
}
void setProperty(int year, int firstDay) {
this.year = year;
this.firstDay = firstDay;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
this.isLeap = true;
month[1] = 29;
} else this.isLeap = false;
}
void outputCalender() {
int startDay = this.firstDay;
int cnt = 0;
int startFlag=0;
int j=0;
for (int i = 0; i < 12; i++) {
if (i < 10) {
System.out.println(this.year + "年" + " " + (i+1) + "月");
} else {
System.out.println(this.year + "年" + (i+1) + "月");
}
System.out.println("----------------------------");
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
for (j = 1,cnt=0; j <= this.month[i]; ) {
if(cnt<startDay&&startFlag==0){
if(cnt+1==startDay)
{
startFlag=1;
}
cnt++;
System.out.print(" ");
continue;
}
if(cnt==startDay&&startFlag==0){
startFlag=1;
}
if(j<10){
System.out.print(" "+j+" ");
}else{
System.out.print(" "+j+" ");
}
if(cnt==6||j==this.month[i])
{
System.out.println();
}
if(cnt>=6&&j!=this.month[i]){
cnt=-1;
}
j++;
cnt++;
}
System.out.println("----------------------------");
startDay=cnt;
if(startDay>=7) startDay=0;
//System.out.println("startday="+startDay);
startFlag=0;
cnt=0;
}
}
}
public class calendar {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int year;
int firstDay;
System.out.print("输入年份: ");
year = reader.nextInt();
System.out.print("该年第1天是星期几: ");
firstDay = reader.nextInt();
CalendarDetail myCalendar = new CalendarDetail();
myCalendar.setProperty(year, firstDay);
myCalendar.outputCalender();
}
}