Since your code has the constant MIDNIGHT
, I'm assuming that the Time
class represents times of day .
So simply adding 1 to minutes can bring invalid values when you have Time
representing 15:59, for example. By simply adding 1 to the minutes, you will end up with the value corresponding to 15:60 (and then 15:61, 15:62, and so on), when the correct value would be 16:00 (and then 16:01 , 16:02, etc.).
So you should add 1 to the minutes and adjust the value if it is 60. For this we use the %
operator, which returns the rest of the division. To ensure that the next minute is between 0 and 59, you can (this.minutes + 1) % 60
.
Then, if the minute value is zero, the hour value must be set to the next hour. I'm assuming that the hours can not also exceed valid values, and that after 23:59, the next value is 00:00. So, I also use the %
operator, but now with the value 24 (ensuring that the times have values between 0 and 23).
So, the tick()
method looks like this:
public Time tick() {
int proximaHora = this.hours;
int proximoMinuto = (this.minutes + 1) % 60;
// se o próximo minuto é zero, deve ir para a próxima hora
if (proximoMinuto == 0) {
proximaHora = (proximaHora + 1) % 24;
}
return new Time(proximaHora, proximoMinuto);
}
In addition, it would be interesting for the builder to validate received values to prevent you from creating invalid times such as 99:99. If the values are invalid, you can throw a IllegalArgumentException
(which is the native exception used to indicate that an invalid parameter has been passed):
public Time(int h, int m) {
if (h < 0 || h > 24) {
throw new IllegalArgumentException("Valor inválido para as horas: " + h);
}
if (m < 0 || m > 59) {
throw new IllegalArgumentException("Valor inválido para os minutos: " + m);
}
hours = h;
minutes = m;
}