java——万年历

java——万年历【代码】java——万年历。

利用Java来实现万年历 

package demo;

import java.util.Scanner;


public class CalendarTest {
    public static void main(String[]args) {
        Scanner sc = new Scanner(System.in);
        Calendar c = new Calendar();
        System.out.println("请输入年份:");
        int year = sc.nextInt();
        System.out.println("请输入月份:");
        int month = sc.nextInt();
        c.show(year,month);
    }
}




class Calendar{
    //判断闰年和平年
    public boolean isLeapYear(int year){
        return ((year % 4 == 0)&&(year % 100 != 0)||(year % 400 == 0));
    }
    //获取指定月份的天数
    public int getTotalDaysOfMonth(int year,int month){
        int total;
        //判断月
        switch (month){
            case 1: case 3: case 5: case 7: case 8: case 12: case 10:
                total = 31;
                break;
            case 2:
                total = (isLeapYear(year)?29:28);
                break;
            default:
                total = 30;
                break;
        }
        return total;
    }
    public int getWeekOfMonth(int year,int month){
        int total = 0;
        for (int i = 1; i < year; ++i){
            total += (isLeapYear(year)?366:365);
        }
        for (int i = 1; i < month; ++i){
            total += getTotalDaysOfMonth(year,i);
        }
        total %= 7;
        total = (total+1)%7;
        return total;
    }
    public void show(int year,int month){
        System.out.println("\033[1;95m"+"\t\t"+" "+year+"年"+month+"月");
        System.out.println("\033[1;96m"+"---------------------------");
        String[] week = {"日","一","二","三","四","五","六"};
        for(int i = 0; i < 7; ++i){
            if(week[i].equals("六") || week[i].equals("日")) System.out.print("\033[32m"+week[i]+"\t");
            else System.out.print("\033[33m"+week[i]+"\t");
        }
        System.out.println();
        int weeks = getWeekOfMonth(year,month);
        for (int i = 0; i<weeks; ++i) System.out.print("\t");
        int days = getTotalDaysOfMonth(year,month);
        for (int i = weeks,j = 1; j <= days; ++i,++j){
            if (i % 7 == 0 || i % 7 == 6)System.out.print("\033[32m"+j+"\t");
            else System.out.print("\033[33m"+j+"\t");
            if ((i+1) % 7 ==0) System.out.println();
        }
        System.out.println();
    }
}

实现:

java——万年历

 

今天的文章java——万年历分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/31344.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注