用java写一个简易日历

写一个简易日历

记录学习之路,用java语言,用的IDEA编辑器。
我觉得写日历一定要有两个首要方法,所以我首先先写了两个方法,一个是判断是否是闰年,方法代码如下

static boolean judgeyear(int year){

            if (year % 4 == 0 && year % 100 != 0   ||  year % 400 ==0){
                return true;
            }else{
                return false;
            }

    }

再准备阶段写了一个计算这个月多少天的方法,用了switch得出这个月有多少天。

static int getData(int year,int month){

        int days=0;
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12: days=31;break;
            case 4:
            case 6:
            case 9:
            case 11: days=30;break;
            default:
                boolean ye=judgeyear(year);
                if (ye=false){
                    days=29;
                }else{
                    days=28;
                }

        }
        return days;
    }

准备工作差不多了,我们理理思维,主函数里面要放些啥,输入函数scanner肯定不能少。

Scanner sc=new Scanner(System.in);
        System.out.println("请输入年份:");
        int year=sc.nextInt();
        System.out.println("请输入月份:");
        int month=sc.nextInt();
        System.out.println("请输入日期:");
        int day=sc.nextInt();

到了这里可以测试一下刚才写的方法看有没有问题。

int days=getData(year,month);
        System.out.println(year+"年"+month+"月,有"+days+"天");

我试了一下,应该是没问题的哈
测试
测试完了,我们开始正事,从1900年1月1号开始我们计总数,然后模7得星期。

//计算1900年1月1号到year年1月1号的总天数
        int totals=0;
        for(int i=1900;i<year;i++){
            if(judgeyear(i)){
                totals+=366;
            }else{
                totals+=365;
            }
        }

        //累加到year的1月到month的总天数
        for (int i=1;i<month;i++){
            totals+=getData(year,i);
        }
        //多加1天得到到year年month月的1号有多少天
        totals+=1;
        //对7取余得到这天是星期几
        int weekday=totals%7;
        System.out.println("1900年1月1号到"+year + "年" + month + "月有:" + totals + "\n这个月的第一天是星期 "+weekday);

到这里再循环几次输出基本就差不多了。

System.out.println("============================================================");
        
        System.out.println(year + "年" + month + "月" );
        System.out.println("一\t二\t三\t四\t五\t六\t日");
        for (int i=1;i<weekday;i++){
            System.out.print("\t");
        }
        for (int i=1;i<=days;i++){
            if(i==day){
                System.out.print("*"+i+"*\t");
            }else{
                System.out.print(i+"\t");
            }
            if((i+weekday-1)%7==0){
                System.out.println();
            }
        }
    }

最后测试一下最后测试
时间就用今天的测试的,暂时好像还没有问题,简易日历。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值