Reputation: 308
I'm trying to make a clock class in Java that will display military time, and my teacher has given us a ClockTester.java that uses our "engine" of a clock. I've gotten it to display correctly, but I'm having trouble adding time correctly.
It's all displayed in military time, so adding 12:00:00 and 15:00:00 should give me 03:00:00, not 27:00:00 like it is giving me... But I'm having trouble doing that.
Here are my (NEW) math methods:
public void addHours(int h){
int sum = this.hours + h; //Keeps the hours value within real boundaries
this.hours += (sum % 24);
}
public void addMinutes(int m){
int sum = this.mins + m;
this.addHours(m / 60);
this.mins += (sum % 60);
}
public void addSeconds(int s){
int sum = this.secs + s;
this.addMinutes(s / 60);
this.secs += (sum % 60);
}
public void addTime(int h, int m, int s){
addHours(h);
addMinutes(m);
addSeconds(s);
}
Please let me know if you need to see/know anything else to help me. Thanks.
Upvotes: 0
Views: 712
Reputation: 1969
What you should do is include a while loop so and loop it down. While the time is greater than 24:00:00 (or its equivalent in seconds: 84600), you should subtract 24 hours. In addTime(...) {...} add:
while (hours*3600 + mins*60 + secs > 84600) {
hours -= 24;
}
You may be just as well of with an if() statement because the time will never be greater than 48 hours. But just to play it safe, use the while. If statement format:
if (hours*3600 + mins*60 + secs > 84600) {
hours -= 24;
}
Upvotes: 0
Reputation: 49
If you are starting off with 15 in your add hours method then its going to first take the modulus of 24 which is 12. Then its going to add that to your original amount and make 27. What you need to do is add a check to see if you have passed, 24 or 60 and rather than have it add, have it reset.
public void addHours(int h){
int sum = this.hours + h;
this.hours += (sum % 24);
}
Upvotes: 2