Java打印某年某月的日历~不调用函数

渡星河
2022-11-11 / 0 评论 / 74 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月11日,已超过674天没有更新,若内容或图片失效,请留言反馈。

这个题目说真的有点难搞哦,又不调用函数,思路想到自闭,很不幸我还是做出来了

我们这边打印一个2022年5月的日历,先给大家看看百度的日历

5月日历
当然我们的代码是做不出这样的,我们看看代码怎么写的

import java.util.Scanner;

public class Work4 {
 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 total=0;
     System.out.println("---------"+year+"年"+month+"月---------\n");
     System.out.println("一\t二\t三\t四\t五\t六\t日");
     //计算1900年到任一年份一月一日是星期几
     //注意比如year是2022年计算到的是2021年最后的天数
     for(int i =1900;i<year;i++){
       //判断是否是闰年
         if((i%4)==0 && (i%100) !=0 || (i%400)==0){
             total+=366;
         }else {
             total+=365;
         }
     }
    
     //如果当年是闰年
     boolean pdyear = (year % 4) == 0 && (year % 100) != 0 || (year % 400) == 0;
   //计算一月到你需要的月份的天数有多少
     for(int i = 1; i<month; i++){
       //小月就是30
         if(i==4||i==6||i==9||i==11){
             total+=30;
         }else if(i==2){
           //二月这里需要区分是什么年,上面表达式计算布尔值
             if(pdyear){
                 total+=29;
             }else{
                 total+=28;
             }
           //否则就是大月
         }else{
             total+=31;
         }
     }
     //计算出那个月有多少天
     int day;
     if(month==4||month==6||month==9||month==11){
         day=30;
     }else if(month==2){
         if(pdyear){
             day=29;
         }else{
             day=28;
         }
     }else{
         day=31;
     }
     //计算出那个月份的1号是星期几
     int week = (total+1)%7;
     //计算需要空出的空间
     int tab;
     if (week == 0) {
         tab=6;
     }else {
         tab = week-1;
     }
     for(int t = 1;t<=tab;t++){
         System.out.print("\t");
     }
     for(int d = 1;d<=day;d++){
         
         if((total+d)%7==0){
             System.out.println(d);
         }else{
             System.out.print(d+"\t");
         }
     }
     
 }
}

我们看一下运行结果,不会的评论,这边邮件提醒回复快

结果

1

评论 (0)

取消