java打印日历

打个日历,写了半天,感情水平真菜, 不过主要是不会数组,明天一定要把数组看了

package demo;
import java.util.Scanner;
public class Demo {
    /*
     * 需求:输入一个年份,以及这年的第一天的星期数(数字表示, 0表示星期日,1表示星期1……)
     *             要求打印这一年每个月的日历
     * 
     * 分析:只要知道这个月的天数daysOfMonth和第一天的星期数startDay就可以打印出这个月的日历
     *        startDay的数值即打印这个月的日历的时候再第一行打印的空格数 ,然后逐个打印这个月的每一天
     *         根据(startDay+daysOfMonth)算出下个月的第一天的星期数
     *         再打印……
     * */
    public static void main(String[] args){
        System.out.print("Enter full year:");
        Scanner sc = new Scanner(System.in);
        int year = sc.nextInt();
        System.out.print("Enter the day of first day:");
        int startDay = sc.nextInt();
        int month = 0, dayOfMonth = 0;
        String monthName = "";
        for(month = 1; month <= 12; month++){
            //确定每个月的天数
            switch(month){
            case 1: case 3: case 5: case 7:case 8: case 10:
            case 12:
                dayOfMonth = 31; break;
            case 2:
                if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
                    dayOfMonth = 29;
                else
                    dayOfMonth = 28; break;
            case 4: case 6: case 9:
            case 11:
                dayOfMonth = 30;
            }
            //确定每个月的名字
            switch(month){
            case 1: monthName = "January"; break;
            case 2: monthName = "February"; break;
            case 3: monthName = "March"; break;
            case 4: monthName = "April"; break;
            case 5: monthName = "May"; break;
            case 6: monthName = "June"; break;
            case 7: monthName = "July"; break;
            case 8: monthName = "August"; break;
            case 9: monthName = "September"; break;
            case 10: monthName = "October"; break;
            case 11: monthName = "November"; break;
            case 12: monthName = "December"; break;
            }
            //打印这个月的日历
            System.out.println("\t  "+ monthName +"    "+year);
            print(dayOfMonth, startDay);
            startDay = (dayOfMonth+startDay) % 7;
        }
    }
    public static void print(int dayOfMonth, int startDay){
        System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
        System.out.println("----------------------------");
        for(int i = 0; i < startDay; i++)
            System.out.print("    ");
        for(int i = 1; i <= dayOfMonth; i++){
            System.out.printf("%4d", i); //原来可以用printf啊!!!哈哈哈~~~~~
            if((i + startDay) % 7 == 0)
                System.out.println();
        }
        System.out.println();
    }

}

 

posted on 2015-10-09 19:19  张明明_1  阅读(297)  评论(0编辑  收藏  举报

导航