首页 > 代码库 > 学习java的简单例子之万年历

学习java的简单例子之万年历

import java.util.Scanner;

public class Calender {

	public static boolean isRun(int year)//判断是否为闰年
	{
		if((year%4==0 && year%100!=0) || (year%400==0))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	public static int calDay(int year,int mth)//判断某年的哪月多少天
	{
		int days=31;
		switch(mth)
		{
		case 4:
		case 6:
		case 9:
		case 11:
		   days=30;
		   break;
		case 2:
			if(isRun(year))
			{
				days=29;
			}
			else
			{
				days=28;
			}
			break;
		}
		return days;
		
	}
	public static int calFirstDay(int year,int mth)//判断是某年哪月第一天是周内第几天
	{
		int FirstDay=0;
		//1900-01-01 星期一
		int i=1901;
		int tmpday=0;
		for(i=1900;i<year;i++)
		{
			if(isRun(i))
				tmpday=tmpday+366;
			else
				tmpday=tmpday+365;
		}
		int h=1;
		for(h=1;h<mth;h++)
		{
			tmpday=tmpday+calDay(year,h);
		}
		FirstDay=tmpday%7;
		return FirstDay;
	}
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
          int year,mth;
          Scanner ysc=new Scanner(System.in);
          System.out.println("请输入年份:");
          year=ysc.nextInt();
          if(isRun(year))
          {
        	  System.out.println(year+"是闰年");
          }
          System.out.println("请输入月份:");
          mth=ysc.nextInt();
          ysc.close();
          System.out.println("**********万年历********"+year+"年"+mth+"月"+"*****************");
             
          System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
          int countTimes=0;
          for(int i=0;i<=calFirstDay(year,mth);i++)
          {
        	  System.out.print("\t");
        	  countTimes++;
          }
          for(int lp=1;lp<=calDay(year,mth);lp++)
          {
        	  System.out.print(lp+"\t");
        	  countTimes++;
        	  if(countTimes%7==0)
        	  {
        		  System.out.println(); 
        	  }
          }
	}

}

学习java的简单例子之万年历