flwy_h flwy_h - 4 months ago 35
Java Question

Using Calendar in while-loop?

The code below does what I want except for the very last output.

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1986, 8, 20);
int year = cal.get(Calendar.YEAR);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
while (year >= cal.get(Calendar.YEAR)) {
cal.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(sdf.format(cal.getTime()));
}


Here is the output:

1986-09-27
1986-10-04
1986-10-11
1986-10-18
1986-10-25
1986-11-01
1986-11-08
1986-11-15
1986-11-22
1986-11-29
1986-12-06
1986-12-13
1986-12-20
1986-12-27
1987-01-03


I'm going to use this while loop to execute irreversible code and I want it to be when the year is NOT 1987. However, the 1987 shows up here and I've tried modifying the while loop condition to get the LAST entry to be

1986-12-27

but to no avail.

The desired output is the same as the output above except without the 1987 date.

Answer

Your loop is performing the add after it's performing the check. So you probably just want:

while (year >= cal.get(Calendar.YEAR)) {
    System.out.println(sdf.format(cal.getTime()));
    cal.add(Calendar.DAY_OF_MONTH, 7);
}

That will change the first value used, however - so you may want an extra add call before the start of the loop, if you want the same first value that you're printing at the moment.