The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Modifiers

As an example of a modifier, consider increment, which adds a given number of seconds to a Time object. Again, a rough draft of this method looks like:

  public static void increment (Time time, double secs) {
    time.second += secs;

    if (time.second >= 60.0) {
      time.second -= 60.0;
      time.minute += 1;
    }
    if (time.minute >= 60) {
      time.minute -= 60;
      time.hour += 1;
    }
  }

The first line performs the basic operation; the remainder deals with the same cases we saw before.

Is this method correct? What happens if the argument secs is much greater than 60? In that case, it is not enough to subtract 60 once; we have to keep doing it until second is below 60. We can do that by simply replacing the if statements with while statements:

  public static void increment (Time time, double secs) {
    time.second += secs;

    while (time.second >= 60.0) {
      time.second -= 60.0;
      time.minute += 1;
    }
    while (time.minute >= 60) {
      time.minute -= 60;
      time.hour += 1;
    }
  }

This solution is correct, but not very efficient. Can you think of a solution that does not require iteration?



Last Update: 2011-01-24