简单用java实现打印任一年的日历
/**
*
* java范例大全
* 打印日历
*
*
*/
package com.zf.s3;
import java.io.*;
public class TextContorl {
static int year,monthDay,weekDay;
public static boolean IsLeapYear(int y) //判断是否是闰年
{
return ((y%4==0&&y%100!=0)||(y%400==0));
}
public static int firstDay(int y) //判断第一天是星期几
{
long n=y*365;
for(int i=1;i<y;++i)
if(IsLeapYear(i))
++n;
return (int)(n%7);
}
public static void printWeek() //打印表头
{
System.out.println("===============================");
System.out.println("日 一 二 三 四 五 六");
}
public static int getMonthDay(int m) //获取每个月的天数
{
switch (m)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if(IsLeapYear(year))
return 29;
else
return 28;
default:
return 0;
}
}
public static void printMonth() //打印
{
for(int m=1;m<=12;++m)
{
System.out.println(m+"月");
printWeek();
for(int j=1;j<=weekDay;++j)
System.out.print(" "); //此处为print而不是println
//print只打印,println打印后换行2
int monthDay=getMonthDay(m);
for(int d=1;d<=monthDay;++d) //格式化
{
if(d<10)
System.out.print(d+" ");
else
System.out.print(d+" ");
weekDay=(weekDay+1)%7; //打印一天后,计算下一天是星期几
if(weekDay==0)
System.out.println();
}
System.out.println('\n');
}
}
public static void main(String[] args)throws IOException
{
System.out.println("请输入一个年份:");
InputStreamReader ir;
BufferedReader in;
ir=new InputStreamReader(System.in);
in=new BufferedReader(ir);
String s=in.readLine();
year=Integer.parseInt(s);
weekDay=firstDay(year);
System.out.println("\n "+year+"年 ");
printMonth();
}
}