首页 > 代码库 > 日历 练习

日历 练习

import java.util.*;public class Calendar {    int year = 0;    int month = 0;    int sum = 0;    int weekday;    int monthday = 0;    public void check() {        System.out.println("先输入年份:");        Scanner sc = new Scanner(System.in);        int year = sc.nextInt();        if (year < 1990 || year > 2100) {            System.out.println("输入非法");            return;        }        System.out.println("在输入月份:");        int month = sc.nextInt();        if (month < 1 || month > 12) {            System.out.println("输入非法");            return;        }        for (int i = 1990; i < year; i++) {            if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {                sum += 366;            } else {                sum += 365;            }        }        for (int i = 1; i < month; i++) {            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {                if (i == 2) {                    sum += 29;                } else if (i == 4 || i == 6 || i == 9 || i == 11) {                    sum += 30;                } else {                    sum += 31;                }            } else {                if (i == 2) {                    sum += 28;                } else if (i == 4 || i == 6 || i == 9 || i == 11) {                    sum += 30;                } else {                    sum += 31;                }            }        }        weekday = (sum += 1) % 7;        // System.out.println(weekday);        System.out.println("日\t一\t二\t三\t四\t五\t六");        for (int i = 0; i <= weekday; i++) {            if (i == weekday) {                System.out.print("1\t");                if (sum % 7 == 6) { // 余数得6的为周六,换行                    System.out.print("\n");                }                sum += 1;                break;            }            System.out.print("\t");        }        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {// 是否为闰年            if (month == 2) {                monthday = 29;            }            else if (month == 4 || month == 6 || month == 9 || month == 11) {                monthday = 30;            } else {                monthday = 31;            }        } else {            if (month == 2) {                monthday = 28;            } else if (month == 4 || month == 6 || month == 9 || month == 11) {                monthday = 30;            } else {                monthday = 31;            }        }        for (int i = 2; i <= monthday; i++) {            if (sum % 7 == 6) { // 余数得6的为周六,换行                System.out.print(i + "\n");                sum += 1;            } else {                System.out.print(i + "\t");                sum += 1;            }        }    }}

基础差这点东西搞好久

主要区分平年闰年,算1990至查询月份的1号共多少天    天数%7   模为1号的星期数,并且打印时周六(天数%7模为6的)换行

日历 练习