I am doing on a java assignment which involves time that displays seconds, minutes and hours.I am required to display time that is moved forward and backwards by few seconds. I am able to enable time to move forward by one second, however, I have difficulty allowing time to be rewinded backwards as my output is kind of weird
For instance, the desired output is supposed to show this:
01:02:03
04:05:06
Hour:·4
Minute:·5
Second:·6
23:59:58
23:59:59
00:00:01
00:00:00
23:59:58
However, my program shows this instead:
01:02:03
04:05:06
Hour: 4
Minute: 5
Second: 6
23:59:58
23:59:59
00:00:01
00:00:00
00:00:-2
The bottom output is the 00:00:-2 which is my output which shows the error. I would appreciate if someone can help me on that. Many thanks!
Attached below is my codings:
public class Time {
private int hour;
private int minute;
private int second;
public Time(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public int getHour()
{
return hour;
}
public int getMinute()
{
return minute;
}
public int getSecond()
{
return second;
}
public void setHour(int hour)
{
this.hour = hour;
}
public void setMinute(int minute)
{
this.minute = minute;
}
public void setSecond(int second)
{
this.second = second;
}
public void setTime(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public String toString()
{
return String.format("%02d:%02d:%02d", hour, minute, second);
}
public Time nextSecond()
{
second++;
if (second == 60)
{
second = 0;
minute++;
if (minute == 60)
{
minute = 0;
hour++;
if (hour == 24)
{
hour = 0;
}
}
}
return this;
}
public Time previousSecond()
{
second--;
if (second == 60)
{
second = 0;
minute--;
if (minute < 60)
{
minute = 0;
hour--;
if (hour < 24)
{
hour = 0;
}
}
}
return this;
}
public static void main(String[] args) {
// Test constructors and toString()
Time t1 = new Time(1, 2, 3);
System.out.println(t1); // toString()
// Test Setters and Getters
t1.setHour(4);
t1.setMinute(5);
t1.setSecond(6);
System.out.println(t1); // toString()
System.out.println("Hour: " + t1.getHour());
System.out.println("Minute: " + t1.getMinute());
System.out.println("Second: " + t1.getSecond());
// Test setTime()
t1.setTime(23, 59, 58);
System.out.println(t1); // toString()
// Test nextSecond();
System.out.println(t1.nextSecond());
System.out.println(t1.nextSecond().nextSecond());
// Test previousSecond()
System.out.println(t1.previousSecond());
System.out.println(t1.previousSecond().previousSecond());
}
}