S'il vous plaît vérifier le code ci-dessous:
/**
* Print all the months which has five Mondays, Saturdays and Sundays
* @param from year from
* @param to year to
*/
public void printMonths(int from, int to) {
List<String> monthList = new ArrayList<String>();
for (int year =from; year<=to;year++) {
monthList.addAll(getMonth(year));
}
for (String s : monthList) {
System.out.println(s);
}
}
/**
* Get month with five sundays, saturdays and mondays
* @param year
* @return
*/
private List<String> getMonth(int year) {
List<String> monthList = new ArrayList<String>();
for (int month = 0; month < 12; month++) {
if (check(year, month)) {
monthList.add("" + year + "-" + (month+1));
}
}
return monthList;
}
private boolean check(int year, int month) {
return checkFiveDays(year, month, 1) && checkFiveDays(year, month, 2)
&& checkFiveDays(year, month, 7);
}
private boolean checkFiveDays(int year, int month, int dayOfWeek) {
Calendar c = Calendar.getInstance();
c.set(year, month, 0, 0, 0, 0);
int times = 0;
do {
if (c.get(Calendar.DAY_OF_WEEK) == dayOfWeek) {
times++;
}
c.add(Calendar.DAY_OF_MONTH, 1);
} while (c.get(Calendar.MONTH)== month);
return times == 5;
}
Il y a des mois qui ont 5 samedis avec moins de 31 jours. Aussi la règle de commencer un samedi n'est pas obligatoire aussi. Vois ma réponse. – dan
Mais si le PO doit avoir tout le samedi..Lundi cinq fois alors les règles sont valides. – dan