How to print every month between two years that contains five full weekends (Fri, Sat, Sun) in Java

1 Answer

0 votes
// A month has five full weekends when it has 31 days,
// and the 1st day of the month is a Friday.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;


// ------------------------------------------------------------
// Function: returns true if a month has 5 full weekends
// ------------------------------------------------------------
public class FiveFullWeekends {

    // ------------------------------------------------------------
    // Month names as a single reusable constant
    // ------------------------------------------------------------
    class CalendarData {
        static final String[] monthNames = {
            "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"
        };
    }
    
    static boolean hasFiveFullWeekends(int year, int month) {
        LocalDate firstDay = LocalDate.of(year, month, 1);

        int daysInMonth = firstDay.lengthOfMonth();
        DayOfWeek weekday = firstDay.getDayOfWeek(); // Monday=1 ... Friday=5

        return (daysInMonth == 31 && weekday == DayOfWeek.FRIDAY);
    }

    // ------------------------------------------------------------
    // Main program
    // ------------------------------------------------------------
    public static void main(String[] args) {
        int startYear = 2026;
        int endYear   = 2030;

        for (int y = startYear; y <= endYear; y++) {
            System.out.print(y + " ");

            for (int m = 1; m <= 12; m++) {
                if (hasFiveFullWeekends(y, m)) {
                    System.out.println(
                        "\n" + CalendarData.monthNames[m - 1] + " " + y +
                        " has five full weekends."
                    );
                }
            }
            System.out.println();
        }
    }
}


/*
run:

2026 
May 2026 has five full weekends.

2027 
January 2027 has five full weekends.

October 2027 has five full weekends.

2028 
December 2028 has five full weekends.

2029 
2030 
March 2030 has five full weekends.

*/

 



answered 7 hours ago by avibootz

Related questions

...