Core Java (六) 打印指定月份的日历

更改的core java的一个程序,利用了GregorianCalendar这个类。

输入年份以及月份,打印出指定月份的日历。

package com.xujin;

import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Scanner;

public class Test {
	static Scanner cin = new Scanner(System.in);
	public static void main(String[] args){
		Locale.setDefault(Locale.US);//设置为美国地区
		System.out.print("Please input the year and month(like 1999 9):");		
		int year = cin.nextInt();
		int month = cin.nextInt();		
		GregorianCalendar day = new GregorianCalendar();//从公元 4 年 3 月 1 日之后是准确的
		
		//将day设置为该月的第一天
		day.set(Calendar.YEAR, year);
		day.set(Calendar.MONTH, month - 1);		
		day.set(Calendar.DAY_OF_MONTH, 1);
		
		int weekday = day.get(Calendar.DAY_OF_WEEK);		
		int firstDayOfWeek = day.getFirstDayOfWeek();
		
		int indent = 0;
		while(weekday != firstDayOfWeek){
			indent++;
			day.add(Calendar.DAY_OF_MONTH, -1);
			weekday = day.get(Calendar.DAY_OF_WEEK);
		}
		
		String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();	
		do{
			System.out.printf("%4s", weekdayNames[weekday]);
			day.add(Calendar.DAY_OF_MONTH, 1);
			weekday = day.get(Calendar.DAY_OF_WEEK);
		}while(weekday != firstDayOfWeek);
		System.out.println();
		
		for(int i = 0; i < indent; i++)
			System.out.print("    ");
		day.set(Calendar.DAY_OF_MONTH, 1);
		
		do{
			int d = day.get(Calendar.DAY_OF_MONTH);
			System.out.printf("%4s", d);
			
			day.add(Calendar.DAY_OF_MONTH, 1);
			weekday = day.get(Calendar.DAY_OF_WEEK);
			
			if(weekday == firstDayOfWeek) System.out.println();
		}while(month - 1 == day.get(Calendar.MONTH));
		
		if(weekday != firstDayOfWeek) System.out.println();
	}
	
}


结果:

Core Java (六) 打印指定月份的日历_第1张图片

你可能感兴趣的:(java,java,java)