java 日历格式转化改进版

来源:互联网 发布:如何评价詹姆斯知乎 编辑:程序博客网 时间:2024/05/29 19:29

java 日历格式转化改进版

标签:java基础

原始版链接
二者的区别:

1.原始版,不修改CalendarBean.java文件,只改了Example8_16.java,也就是说,只是改变了日历的输出顺序。2.改进版,修改了CalendarBean.java(改变了日历的存储顺序),而日历的输出顺序不变(Example8_16.java改了日历的表头)。
//Example8_16import java.util.*;public class Example8_16 {    public static void main(String[] args)     {        CalendarBean cb = new CalendarBean();        System.out.printf("please input year and month: ");  //输入年份和月份        Scanner reader = new Scanner(System.in);        int year = 0, month = 0;        cb.setYear(year = reader.nextInt());        cb.setMonth(month = reader.nextInt());        String [] a = cb.getCalendar();  //返回号码的一维数组        char [] str = "一二三四五六日".toCharArray();  ////修改表头        System.out.printf("----------------------------\n%14d.%-2d\n", year, month);  //打印表头        System.out.printf("----------------------------\n");        for(char c : str)  System.out.printf("%3c", c);        for(int i = 0; i < a.length; i++)  //输出数组a        {            if(i % 7 == 0)  System.out.println("");  //换行            System.out.printf("%4s", a[i]);        }    }}
//CalendarBeanimport java.util.Calendar;public class CalendarBean{    int year = 0, month = 0;    public void setYear(int year)    {        this.year = year;    }    public void setMonth(int month)    {        this.month = month;    }    public String [] getCalendar()    {        String [] a = new String[42];  //日历最多可达6行        Calendar rili = Calendar.getInstance();        rili.set(year, month - 1, 1);  //模拟翻日历        int weekDay = rili.get(Calendar.DAY_OF_WEEK) - 2;  ////计算出1号的星期,唯一改动部分,与原始日历格式比较        int day = 0;        if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)  day = 31;        if(month == 4 || month == 6 || month == 9 || month == 11)  day = 30;        if(month == 2)        {            if(((year % 4 == 0) && (year % 100 != 0)) || year % 400 == 0)  day = 29;            else  day = 28;        }        //if(weekDay == 0)  weekDay += 7;        for(int i = 0; i < weekDay; i++)  a[i] = " ";  //日历顺序输出,格式控制        for(int i = weekDay, n = 1; i < weekDay + day; i++)        {            a[i] = String.valueOf(n);            n++;        }        for(int i = weekDay + day; i < a.length; i++)  a[i] = " ";        return a;    }}

修改后的日历测试样例:
test1
test2
test3