Java representing time class -
i want represent time time class. can't use , set methods.only can use listed methods on code.but doesn't work. returns 0:0:0.
public int addhours(int hours) { if(hours>=0&&hours<=23) { return hours; } return 0; } public int addminutes(int minutes) { if(minutes>=0&&minutes<=59) { return minutes; } return 0; } public int addseconds(int seconds) { if(seconds>=0&&seconds<=59) { return seconds; } return 0; } public string showtime() { return hours+":"+minutes+":"+seconds; } }
your code nothing.
you need this:
public void addhours( int hours ){ this.hours += hours; // add hours this.hours %= 24; // roll on @ 24 hours } public void addminutes( int minutes ){ this.minutes += minutes; // add minutes addhours(this.minutes/60); // carry on hours this.minutes %= 60; // roll on @ 60 minutes } public void addseconds( int seconds ){ this.seconds += seconds; // add seconds addminutes(seconds/60); // carry on minutes this.seconds %= 60; // roll on @ 60 seconds }
(it won't matter, not thread safe @ all)
but bad idea. java 8 has beautiful time api, pre java-8 there jodatime library (which basis of java 8 time api). seems want benefit localtime:
localtime t = localtime.of(13,50,27).addhours(1).addminutes(1).addseconds(1); system.out.println(t.tostring()); // prints 14:51:28
Comments
Post a Comment