编写万年历(要求输入年份和月份打印这个月的日历)

public static void main(String[] args){
  Scanner sc=new Scanner(System.in);
  System.out.println("请输入一个年份:");
  //接收年份
  int year=sc.nextInt();
  System.out.println("请输入一个月份:");
  //接收月份
  int month=sc.nextInt();
  //累计跨年的天数
  int yearTotal=0;
  //计算跨年的天数(当年的不能算,不然整年的天数都加上了)
  for(int i=1900;i<year;i++){
    //闰年加366
    if(i%4==0&&i%100!=0||i%400==0){
      yearTotal+=366;
    }
    //平年加365
    else{
      yearTotal+=365;
    }
  }

  //累计跨月总天数
  int monthTotal=0;
  //记录每月的天数
  int day=0;
  //i<=month方便后面计算的当月有多少天,但是计算这个月之前总天数时,不能加上本月,所以后面加总的时候要判断
  for(int i=1;i<=month;i++){
    switch(i){
      case 2:day=year%4==0&&i%100!=0||i%400==0?29:28;
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        day=30;
        break;
      default:
        day=31;
      //只要不等于当月的天数,则累计加总
      if(i<month){
        monthTotal+=day;
      }
    }
  }

  //记录本月1号是否被7整除,余数是多少,就是周几
  int week=(yearTotal+monthTotal+1)%7;
  System.out.println("本月1号是周"+week);
  //1号是周几,前面对应就有几个\t,循环输入
  System.out.println("日\t一\t二\t三\t四\t五\t六");
  //打印1号前面的空格
  for(int i=1;i<=week;i++){
    System.out.print("\t");
  }
  //打印每个月的日期数
  for(int i=1;i<=day;i++){
    System.out.println(i+"\t");
    if(yearTotal+monthTotal+i%7==6){
      //如果是周六则换行打印
      System.out.println();
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/gfl-1112/p/12657289.html