nextDeparture 🌶️🌶️
Buses leave a stop at the first time and then every every minutes (1 or more). You get to the stop at the time arrive. A bus that leaves at the very moment you arrive can be caught.
Write a method nextDeparture that takes the first bus time, every, and arrive, and returns the time of the first bus you can catch, as text from toString(). Use addMinutes and isBefore. The last bus is always before midnight, and you will always be able to catch one.
For example, with the first bus at 6:00 AM, one every 20 minutes, and you arriving at 7:05 AM, the buses are 6:00, 6:20, 6:40, 7:00, 7:20, so the answer is "7:20 AM".
while (bus.isBefore(arrive)) and move bus to bus.addMinutes(every). When the loop ends, bus is the one you catch: return bus.toString().Reference: Time — the methods you can call
class Time
A time of day on a 24-hour clock, to the minute. Out-of-range values wrap around (25:00 is 1:00, and minute 90 is an hour and a half), so a Time is always a real time of day. A Time never changes once it is made. You do not write this class; make a time with new Time(hour, minute).
Time t = new Time(9, 5);
t.toString() // "9:05 AM"
t.addMinutes(60).toString() // "10:05 AM"
new Time(23, 30).addMinutes(45).toString() // "12:15 AM"
t.isBefore(new Time(13, 0)) // true
t.getHour() // 9
| Method | What it does |
|---|---|
Time(int hour, int minute) | Makes a time. Values out of range wrap around the clock, so
|
int getHour() | The hour on the 24-hour clock. Returns the hour, 0 to 23 |
int getMinute() | The minute. Returns the minute, 0 to 59 |
Time addMinutes(int minutesToAdd) | A NEW time that many minutes later, wrapping past midnight. A negative number goes back.
Returns the new time |
boolean isBefore(Time other) | Whether this time is earlier in the same day than another.
Returns true if this time comes first; false if it is the same or later |
boolean equals(Time other) | Whether another time has the same hour and minute.
Returns true if equal; false otherwise, including for null |
String toString() | The time on a 12-hour clock, such as "9:05 AM" or "12:00 PM". Returns the time as text |