Jack L.
Jack L.

Reputation: 415

Adding time through objects

For this problem, I have to add a mutator instance method into an object called TimeSpan. I am having trouble getting the hours and minutes right when the added minutes are higher than 59; at least I have the hours though.

Here's what I have:

public void add(TimeSpan span) {
    this.hours += span.hours;

    if ((this.minutes + span.minutes) >= 60) { 
        this.hours += (this.minutes + span.minutes)/60;
        this.minutes += (this.minutes + span.minutes)%60;
    } else {
        this.minutes += span.minutes;
    }
}

Upvotes: 0

Views: 1225

Answers (1)

James Oravec
James Oravec

Reputation: 20381

Think it is a simple mistake, you used += when you just need =, update your code to be:

this.minutes = (this.minutes + span.minutes)%60;

Upvotes: 7

Related Questions