CH11 – Pure Methods and Modifiers

  1. If you didn’t complete the Adding Times exercise, do so now.
  2. Open AddingTimes.java and add the following method.
public void increment(int seconds){
  this.second += seconds;
  while(this.second >= 60){
    this.second -= 60;
    this.minute++;
  }
}
  1. Add the following lines to main.
endTime = endTime.increment(120);
System.out.println(endTime.toString());
  1. Compile and run the program.
$ javac AddingTimes.java 
$ java AddingTimes
20:66:0
20:66:0
20:68:0

The complete class should appear as follows.

public class AddingTimes{
  int hour;
  int minute;
  int second;

  public AddingTimes(int hour, int minute, int second){
    this.hour = hour;
    this.minute = minute;
    this.second = second;
  }
  public AddingTimes(){
  }

  public void increment(int seconds){
    this.second += seconds;
    while(this.second >= 60){
      this.second -= 60;
      this.minute++;
    }
  }

  public String toString(){
    return this.hour + ":" + this.minute + ":" + this.second;
  }

  public static AddingTimes add(AddingTimes t1, AddingTimes t2){
    AddingTimes sum = new AddingTimes();
    sum.hour = t1.hour + t2.hour;
    sum.minute = t1.minute + t2.minute;
    sum.second = t1.second + t2.second;
    return sum;
  }

  public AddingTimes add(AddingTimes t2){
    AddingTimes sum = new AddingTimes();
    sum.hour = this.hour + t2.hour;
    sum.minute = this.minute + t2.minute;
    sum.second = this.second + this.second;
    return sum;
  }

  public static void main(String[] args){
    AddingTimes startTime = new AddingTimes(18, 50, 0);
    AddingTimes runningTime = new AddingTimes(2,16,0);
    AddingTimes endTime = AddingTimes.add(startTime, runningTime);
    System.out.println(endTime.toString());

    endTime = startTime.add(runningTime);
    System.out.println(endTime.toString());

    endTime.increment(120);
    System.out.println(endTime.toString());

  }
}