Lab 2010 - Superstition


Which day of the week is the thirteenth of the month most likely to fall upon? Once you have determined how often the calendar repeats itself, use a GregorianCalendar object to cycle through all the days, tallying how many Mondays, Tuesdays, etc. fall on the 13th of each month.

Working with Calendar Dates

Java provides a GregorianCalendar class that is useful for working with dates. The following sequence creates an object d1 that represents the date of October 18, 1947. Be sure to import java.util.* and java.text.*. Be careful: the months are numbered starting at zero, so October is set as 9, not 10.

    GregorianCalendar d1 = new GregorianCalendar();
    d1.set(Calendar.YEAR, 1947);
    d1.set(Calendar.MONTH, 9);
    d1.set(Calendar.DAY_OF_MONTH, 18);

For more information on the calendar, go here. If I want to know what day of the week that date was, I can get the time (a complete date) and format the fields I want.

    SimpleDateFormat df1 = new SimpleDateFormat("MMMM d, yyyy");
    SimpleDateFormat df2 = new SimpleDateFormat("EEEE");
    System.out.print( df1.format(d1.getTime()) + " was a ");   
    System.out.println( df2.format(d1.getTime()) );
For more date formatting information, go here. I could also get the pieces individually, as integers, with code like d1.get(Calendar.DAY_OF_MONTH). You will also want to know that the date can be advanced with d1.add(Calendar.DATE, 1); and that date comparisons are possible: d1.before(d2) returns true or false.

Write the program that calculates how many Mondays, Tuesdays, etc. fall on the 13th of each month. Then report which day the 13th of the month is most like to fall upon.

Copyright © 2010 by Asylum Computer Services LLC Return to CS Labs