java - How can I change my program to allow user input to take the time? -
im struggling on project set myself. want user able input time, needs legal (i.e if time 9:15 , add 4 hours, must 01:15 please help!
package time; public class newtime { int hh, mm; public newtime(int hh, int mm) { if (hh > 0 && hh < 24 && mm > 0 && mm < 60) { this.hh = hh; this.mm = mm; } } public void addtime(int hh, int mm) { if (mm + this.mm > 59) { this.hh += mm / 60; } this.hh += hh; this.mm += mm; } }
your problem lies here:
public void addtime(int hh, int mm) { if (mm + this.mm > 59) { this.hh += mm / 60; } this.hh += hh; //<--source of problem this.mm += mm; } you need check after addition whether hh variable more 12. if more 12 deduct 12. corrected format be:
public void addtime(int hh, int mm) { this.hh += hh; this.mm += mm; this.hh += this.mm / 60; this.mm = this.mm % 60; //this removes problem mm may 59 , this.mm 2 this.hh = this.hh % 12; //this solves problem of hour not getting on 12. } here instead of checking whether sum of this.mm , mm greater 59. add mm this.mm , add integer division result of this.mm / 60 hh. set remainder of integer division this.mm. repeat same thing hh store remainder of integer division of this.hh , 12 give output in 12 hour format.
this should take care of problem.
Comments
Post a Comment