实验2:制作某年某月的日历。
实验2:制作某年某月的日历。
实验目的:掌握Calendar类的使用。
实验要求:通过键盘输入年份和月份,程序输出相应的日历牌。
------解决方案--------------------
import java.io.*;
import java.util.*;
class CalendarTest
{
public static void main(String[] args) throws Exception
{
System.out.print("输入年份: ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
int year = Integer. parseInt(br1.readLine());
for(int i=1; i<=12; i++)
{
System.out.println("*******************************************************");
System.out.println("*\t\t"+year+"年"+i+"月\t\t\t");
System.out.println("*******************************************************");
prin(year, i);
System.out.println();
System.out.println();
}
}
public static void prin(int year, int month)
{
Calendar calendar = new GregorianCalendar();
String week[] = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
for (int i=0; i<week.length; i++ )
{
System.out.print(week[i]+"\t");
}
System.out.print("\n");
int monthDay = 0; //一个月的天数
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
monthDay = 31;break;
case 4:
case 6:
case 9:
case 11:
monthDay = 30;break;
case 2:
monthDay = ((year%4==0&&year%100!=0)||(year%400==0))?29:28;
break;
}
//System.out.println("monthDay = "+monthDay);
calendar.set(year, month-1,1);//设置第一天 通过week[calendar.get(Calendar.DAY_OF_WEEK)-1]拿到第一天是星期几
int count = 0; //记录空格
while (!(week[calendar.get(Calendar.DAY_OF_WEEK)-1].equals(week[count])))
{
count++;
}
for (int j=0; j<count; j++ )
{
System.out.print("\t");
}
for(int i=1; i<=monthDay; i++)
{
calendar.set(year, month-1,i);
System.out.print(" "+i+"\t");
if(week[calendar.get(Calendar.DAY_OF_WEEK)-1].equals("星期六"))
{
System.out.print("\n");
}
}
}
}