Given a LocalTime
add n
minutes to it untill midnight and print those times to console. Example:
public static void main(String[] args) {
LocalTime start = LocalTime.of(10, 12, 0);
LocalTime midnight = LocalTime.of(23, 59, 59);
for (LocalTime t = start; t.isBefore(midnight); t = t.plusMinutes(30)) {
System.out.println(t);
}
}
Expected:
10:12
10:42
11:12
11:42
12:12
...
...
21:42
22:12
22:42
23:12
23:42
The above results in an infinite loop. How to avoid it?
As you are observing, t.isBefore(midnight)
will not suffice, because nearly every LocalTime value will satisfy that condition.
What you really want is to determine whether adding 30 minutes will cause the time to be less than the current value of t
:
for (LocalTime t = start; t.isBefore(t.plusMinutes(30)); t = t.plusMinutes(30)) {
That will stop the loop when adding 30 minutes to t
results in a value which is less than t
itself, which can only happen when the minutes addition wraps around at the end of a day.
But it’s not perfect, because it won’t print the last value of the day. You can do that with a second variable that tracks the previous time:
LocalTime previous = null;
for (LocalTime t = start;
previous == null || previous.isBefore(t);
previous = t, t = t.plusMinutes(30)) {
System.out.println(t);
}