【Java笔试题】通过年月获取详细日历

来源:互联网 发布:java mission control 编辑:程序博客网 时间:2024/06/06 00:38

1、题目

输入年份和月份,打印出当年当月的详细日历。

2、Java代码

import java.util.Calendar;import java.util.GregorianCalendar;import java.util.Scanner;public class GetCalendar {    int month;  //该变量用于存储月    int year;  //该变量用于存储年    public GetCalendar(final int dismonth, final int disyear) {        this.month = dismonth;        this.year = disyear;    }    public String checkMonth() {  //该方法返回月份        String[] months = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"};        return months[month];    }    public int checkDays() {  //该方法返回天        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};        return days[month];    }    public void print() {  //打印日历        int initSpace = 0; //将该月份起始的天数留空        try {  //获取月份名称            String monthName = checkMonth();            System.out.println("");            System.out.println("\t\t\t" + year + "年" + monthName);            System.out.println("");        } catch (Exception ex) {            System.out.println("超出范围.....");            System.exit(0);        }        GregorianCalendar gc = new GregorianCalendar(year, month, 1);        System.out.println("\t日\t一\t二\t三\t四\t五\t六");        //得到该月的第一天是一个星期的第几天,然后预留空格        initSpace = gc.get(Calendar.DAY_OF_WEEK) - 1;        //获取天数        int daysInMonth = checkDays();        //检查是否为闰年,为二月份增加一天(使用isLeapYear()方法判断是否为闰年)        if (gc.isLeapYear(gc.get(Calendar.YEAR)) && month == 1) {            ++daysInMonth;        }        for (int i = 0; i < initSpace; i++) {            System.out.print("\t");        }        for (int i = 1; i <= daysInMonth; i++) {            System.out.print("\t" + i);            if ((initSpace + i) % 7 == 0) {                System.out.println();            }        }        System.out.println("");    }    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        System.out.println("请输入年份:");        int year = s.nextInt();        System.out.println("请输入月份:");        int month = s.nextInt();        GetCalendar vm = new GetCalendar(month - 1, year);        vm.print();    }}