Add 1 minute to hour

4

I have a problem solving an exercise. It may be easy but I can not seem to find the right solution.

I have the following class Time

public final class Time {
      private final int hours;
      private final int minutes;

      public Time(int h, int m) {hours = h; minutes = m;}

      public static final Time MIDNIGHT = new Time(0,0);

      public int getHours() {return hours;}

      public int getMinutes() {return minutes;}

      public Time tick() {
           return null;
      }
}

I have to define the tick() method that should return a new object of type Time corresponding to the addition of one minute over the represented time.

    
asked by anonymous 06.07.2018 / 00:34

1 answer

5

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;
}
    
06.07.2018 / 01:11