Java编程:万年历,根据用户输入的年份,月份,显示日历
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
//根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar=Calendar.getInstance();
System.out.println("<<<<<<<<<<<<<<<<万年历>>>>>>>>>>>>>>>>>>");
int year=0;
int month=0;
System.out.print("请输入年份:");
year=scanner.nextInt();
System.out.print("请输入月份:");
month=scanner.nextInt();
//设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);//月份是0-11
calendar.set(Calendar.DATE, 1);
//得到当前月份的最大值
int day=calendar.getActualMaximum(Calendar.DATE);
//得到本月中的第一天是星期几
int week=calendar.get(Calendar.DAY_OF_WEEK);
int count=0;//一个计数的变量
System.out.println("\n\t\t"+year+" 年 "+month+" 月\n");
//打印日历的星期
String strDate[]={"日\t","一\t","二\t","三\t","四\t","五\t","六\t"};
for (int i = 0; i < strDate.length; i++) {
System.out.print(strDate[i]);
}
System.out.println();
//判断第一天对应的是星期几
while (count<week-1) {
System.out.print("\t");
count++;//计数变量自增
}
//循环打印日历
for (int i = 1; i <= day; i++,count++) {
if (count%7==0) {
System.out.println();
}
System.out.print(i+"\t");
}
}