日历代码

import java.util.*;

public class rili {
 public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out
    .println("********************欢迎使用万年历********************");
  System.out.print("/n请选择年份:");
  int nianfen = input.nextInt();
  System.out.print("/n请选择月份:");
  int yuefen = input.nextInt();
  System.out.println("星期日/t星期一/t星期二/t星期三/t星期四/t星期五/t星期六");

  /* 闰年的条件 */
  boolean run = false;
  if ((nianfen % 4 == 0 && nianfen % 100 != 0) || (nianfen % 400 == 0)) {
   run = true;
  }

  int xiangchatian = 0; // 相差天数
  /* 求相差年共多少天 */
  for (int i = 1900; i < nianfen; i++) {
   if ((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0)) { // 这里条件为i,不是nianfen;
    xiangchatian = xiangchatian + 366;
   } else {
    xiangchatian = xiangchatian + 365;
   }
  }

  /* 求相差月共多少天 */
  int xiangchayue = yuefen - 1; // 相差月
  for (int j = 1; j < yuefen; j++, xiangchayue--) { // 相差月做自减,并循环累加每月天数;
   switch (xiangchayue) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
     xiangchatian = xiangchatian + 31;
     break;
    case 2:
     if (run) {
      xiangchatian = xiangchatian + 29;
     } else {
      xiangchatian = xiangchatian + 28;
     }
     break;
    case 4:
    case 6:
    case 9:
    case 11:
     xiangchatian = xiangchatian + 30;
     break;

   }
  }

  /* 求需要查看的月份第一天是星期几 */
  /* 输出空格 */
  int xingqi = (1 + xiangchatian) % 7;
  for (int kong = xingqi; kong > 0;kong--) {
   System.out.print("/t");
  }

  /* 输出日期 */
  int tianshu = 0;
  switch (yuefen) {
   case 1:
   case 3:
   case 5:
   case 7:
   case 8:
   case 10:
   case 12:
    tianshu = 31;
    for (int i = 1; i <= tianshu; i++, xiangchatian++) {
     System.out.print(i + "/t");
     xingqi = (1 + xiangchatian) % 7;
     if (xingqi == 6) {
      System.out.print("/n");
     }
    }
    break;
   case 2:
    if (run) {
     tianshu = 29;
     for (int i = 1; i <= tianshu; i++, xiangchatian++) {
      System.out.print(i + "/t");
      xingqi = (1 + xiangchatian) % 7;
      if (xingqi == 6) {
       System.out.print("/n");
      }
     }
    } else {
     tianshu = 28;
     for (int i = 1; i <= tianshu; i++, xiangchatian++) {
      System.out.print(i + "/t");
      xingqi = (1 + xiangchatian) % 7;
      if (xingqi == 6) {
       System.out.print("/n");
      }
     }
    }
    break;
   case 4:
   case 6:
   case 9:
   case 11:
    tianshu = 30;
    for (int i = 1; i <= tianshu; i++, xiangchatian++) {
     System.out.print(i + "/t");
     xingqi = (1 + xiangchatian) % 7;
     if (xingqi == 6) {
      System.out.print("/n");
     }
    }
    break;
   default:
    System.out.println("输入月份有误");
 
  }

 }
}

你可能感兴趣的:(日历代码)