Saturday, February 20, 2010

Calendar of a month using Java

import java.util.*;
/*
* Printing the calendar of a month where the user
* Gives the input month , year
* By Shyamala
*/
class CalendarForMonth{
public static void main(String args[]){
//A string array for months

String months []={"Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"};

//An integer for number of days in every month
int nDays[]={31,28,31,30,31,30,31,31,30,31,30,31};

//creating the instance of calendar
Calendar calendar = Calendar.getInstance();

Scanner in = new Scanner(System.in);
//Take the input from the user Month,Year

System.out.print("Enter month ,year :");
int mon = in.nextInt(); int yr = in.nextInt();
calendar.set(yr,mon-1,1); //setting date yr,mon,date consider first day

if(yr%4==0){
System.out.println("Leap year!!");
//change the number of days Feb month as it is leap year
nDays[1]=29;
}

System.out.println("Calendar For "+calendar.get(Calendar.YEAR)+" == "+months[calendar.get(Calendar.MONTH)]);

//printing the days
System.out.print("S\tM\tTu\tW\tTh\tF\tSa");
int day = calendar.get(Calendar.DAY_OF_WEEK);
//System.out.println(day);
System.out.println();

//gives you the starting day
int nline=0;
//for getting new lines

for(int i=1;i<=nDays[mon-1];i++){
System.out.print(i+"\t");
nline++;
if(nline%7==0)
System.out.println("\n");
}

}

}